使用反射更改只读属性 [英] Changing read only properties with reflection

查看:15
本文介绍了使用反射更改只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能吗?是通过反射还是其他方式?

Is it possible? With reflection or any other way?

推荐答案

正如其他人所说,如果您需要这样做,您将面临一个设计问题.现在,如果你想知道这是否可能只是为了知道,或者如果地球上没有其他方法可以做到,这确实是可能的,借助一个非常小的 helper library 和一个扩展方法.

As other stated, if you need to do that, you're facing a design issue to begin with. Now, if you want to know if it's possible just for the sake of knowing, or if there's no other way on earth to do it, it's indeed possible, with the help of a very small helper library and an extension method.

考虑以下代码:

class Person {

    int age;
    string name;

    public int Age { get { return age; } }
    public string Name { get { return name; } }
}

// ...

using Mono.Reflection;
using System.Reflection;

// ...

Person person = new Person (27, "jb");
PropertyInfo nameProperty = typeof (Person).GetProperty ("Name");
FieldInfo nameField = nameProperty.GetBackingField ();
nameField.SetValue (person, "jbe");

使用此代码,您可以仅获取属性的支持字段,并为支持字段分配新值.您可以阅读有关 实施.

Using this code, you can get the backing field of a property with just the property, and assign a new value to the backing field. You can read more details about the implementation.

还要注意,它只适用于简单的属性,例如:

Also note that it works only for simple properties, such as:

public int Age { get { return age; } }

public string Name {
    get { return name; }
    set { name = value; }
}

public double Velocity { get; private set; }

如果您有带有自定义代码的复杂属性(其中包括 表达式主体int Answer=> 42;),支持字段解析器将失败,因为在这种情况下没有支持字段.

If you have complex properties with custom code (which includes expression-bodied member like int Answer=> 42;), the backing field resolver will fail as there is no backing field in such case.

这篇关于使用反射更改只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆