C# 反射动态给属性赋值

C# 反射动态给属性赋值,第1张

public static T PopulateEntityFromCollection<T>(T entity, IDataReader collection) where T : new()

{

//初始化 如果为null

if (entity == null)

{

entity = new T()

}

//得到类型

Type type = typeof(T)

//取得属性集合

PropertyInfo[] pi = type.GetProperties()

foreach (PropertyInfo item in pi)

{

//给属性赋值

if (collection[item.Name] != null)

{

item.SetValue(entity, Convert.ChangeType(collection[item.Name], item.PropertyType), null)

}

}

return entity

}

你可以仿造我以前这个方法写

    public class ReflectDemo

    {

        public static void Main(string[] args)

        {

            // 正常方式创建对象和给属性赋值

            C c = new C()

            c.N = "helloworld"

            // 正常方式赋值

            Console.WriteLine("正常方式赋值:")

            Console.WriteLine(c.N)

            // 全反射方式

            var type = typeof(C)

            object obj = Activator.CreateInstance(type)

            // 属性赋值            

            PropertyInfo pInfo = type.GetProperty("N")

            if (pInfo != null)

            {

                pInfo.SetValue(obj, "helloworld", null)

                // 测试是否已经属性赋值。

                Console.WriteLine("测试是否已经属性赋值:")

                Console.WriteLine(((C)obj).N) 

                // 用反射方式获取属性的值

                Console.WriteLine("用反射方式获取属性的值:")

                Console.WriteLine(pInfo.GetValue(obj, null)) 

            }

            Console.Read()

        }

    }

C类代码如下:

    public class C

    {

        private string n

        public string N

        {

            get { return n }

            set { n = value }

        }

    }


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11740264.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-18
下一篇2023-05-18

发表评论

登录后才能评论

评论列表(0条)

    保存