C# 反射赋值

            tb_Projects model = new tb_Projects();
            model.OwnerId = 123;
            string FieldName = "OwnerId";//字段名称
            string Value = "333";
            Type t = model.GetType();
            
            var p = t.GetProperty(FieldName);
            if (!p.PropertyType.IsGenericType)
            {
                p.SetValue(model, Convert.ChangeType(Value, p.PropertyType), null);
            }
            else
            {
                Type genericTypeDefinition = p.PropertyType.GetGenericTypeDefinition();
                if (genericTypeDefinition == typeof(Nullable<>))
                {
                    p.SetValue(model, Convert.ChangeType(Value, Nullable.GetUnderlyingType(p.PropertyType)), null);
                }
                else
                {
                    throw new Exception("genericTypeDefinition != typeof(Nullable<>)");
                }
            }

            Console.WriteLine(model.OwnerId);
            Console.ReadLine();
public class tb_Projects
    {
       
        public int ProID { get; set; }        
        public string ProjectName { get; set; }
        /// <summary>
        /// 编码
        /// </summary>
        public string ProjectCode { get; set; }
       

        public int ParentId { get; set; }
        public int? NextId { get; set; }
        public int? ProjectOrder { get; set; }

        public int IsEnabled { get; set; }
        /// <summary>
        /// 业主单位id
        /// </summary>
        public int? OwnerId { get; set; }
        /// <summary>
        /// 施工单位ID
        /// </summary>
        public int? ConstructionId { get; set; }
        /// <summary>
        /// 监理单位id
        /// </summary>
        public int? SupervisionId { get; set; }
        /// <summary>
        /// 承包单位id
        /// </summary>
        public int? ContractId { get; set; }

        /// <summary>
        /// 第几级(即在树层次中第几级,根元素级次为1,以此类推)
        /// </summary>
        public int? Level { get; set; }
        /// <summary>
        /// 数量
        /// </summary>
        public int? Quantity { get; set; }


        public int VersionIng { get; set; }

        /// <summary>
        /// 里程桩号
        /// </summary>
        public string MileageNo { get; set; }
        /// <summary>
        /// 标准编码
        /// </summary>
        public string ComponentCode { get; set; }

        /// <summary>
        /// 内部编码
        /// </summary>
        public string NComponentCode { get; set; }

        /// <summary>
        /// 流程状态
        /// </summary>
        public int TaskStatus { get; set; }

        

        public string FbxId { get; set; }
        /// <summary>
        /// 判断是否为单位工程
        /// </summary>
        public int IsSubunit { get; set; }
        /// <summary>
        /// 所属标段
        /// </summary>
        public string BiDSion { get; set; }
    }
View Code
原文地址:https://www.cnblogs.com/guxingy/p/10103176.html