利用反射给类赋值

本文介绍了如何在C#中利用反射技术动态地为类的属性赋值。通过创建一个`ContractDataRecord`类并定义一些属性,然后在`AssembleContractData`类中使用反射来遍历字典,根据键查找对应属性并赋值。如果找到对应的属性名加"Chinese",也会一并赋值。这种方法在需要动态操作对象属性时非常有用。
摘要由CSDN通过智能技术生成
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace TestTask
{
    public class ContractDataRecord
    {
        public string Name { get; set; }


        public string Age { get; set; }
        public string GuaranteeCost { get; set; }
        public string GuaranteeCostChinese { get; set; }
        public string GuaranteeTotal { get; set; }


        public string MonthlyRepay { get; set; }
        public string MonthlyRepayChinese { get; set; }


        public string MothlyInterest { get; set; }


        public string MontlyPrinciple { get; set; }
        public string ServiceCost { get; set; }
        public string AdvanceToB { get; set; }


    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace TestTask
{
    public class AssembleContractData
    {

        static Dictionary<string, string> ComputeData = new Dictionary<string, string>{
           {"GuaranteeCost","50"},
           {"GuaranteeTotal","100"},
           {"MonthlyRepay","200"},
           {"MothlyInterest","400"},
           {"AdvanceToB","500"},
        };

        public static ContractDataRecord BuildContractData()
        {
            ContractDataRecord data = new ContractDataRecord()
            {
                Name = "Smile",
            };

            if (ComputeData != null && ComputeData.Any())
            {
                var type = data.GetType();

                foreach (var item in ComputeData.Keys)
                {
                    try
                    {
                        var field = type.GetProperty(item);
                        if (field != null)
                        {
                            field.SetValue(data, ComputeData[item]);

                            var fieldChinese = type.GetProperty(item + "Chinese");
                            if (fieldChinese != null)
                            {
                                fieldChinese.SetValue(data, ComputeData[item] + "Chinese");
                            }
                        }                        
                    }
                    catch (Exception)
                    {
                        
                        throw;
                    }
                }
            }

            return data;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值