c#中如何利用反射设置属性值

c#中如何利用反射设置属性值,第1张

using System

using System.Reflection

class RowAdapter

{

    private string Name { get set }

    public long Id { get set }

}

class Program

{

    public static void Main(string[] args)

    {

        RowAdapter row = new RowAdapter()

        Type type = typeof(RowAdapter)

        //或者 Type type = row.GetType()

        

        //设置公有属性

        PropertyInfo pubproperty = type.GetProperty("Id")

        pubproperty.SetValue(row, 1)

        

        //设置私有属性

        BindingFlags bindAttr = BindingFlags.Instance | BindingFlags.NonPublic

        PropertyInfo priproperty = type.GetProperty("Name", bindAttr)

        priproperty.SetValue(row, "hello world!")

    }

}

不可以,你可以想像一下,反射发生的时机和步骤。当通过反射获得了指定对象的Class对象之后,此时的对象是存放在堆内存中的,而且已经完成了编译,此时的对象是无法对其进行添加熟悉和方法的。换种思路,如果可以的话,那么修改厚的对象将不再是原有类的对象,那么原有类类型的引用变量引用当前对象势必报错。你可以写个例子试试。

Field field = classType.getDeclaredField("username")

//设置压制访问类型检查,只有这样,才能获取和设置某个具体类的Field对应的值。

field.setAccessible(true)

System.out.println(field.get(privateField))

//设置私有域的值

field.set(privateField, "arthinking")

System.out.println(field.get(privateField))


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

原文地址: http://outofmemory.cn/tougao/11170396.html

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

发表评论

登录后才能评论

评论列表(0条)

保存