更改只读与反射特性 [英] Changing read only properties with reflection

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

问题描述

这可能吗?随着反射或任何其他方式?

Is it possible? With reflection or any other way?

推荐答案

至于其他规定,如果你需要,你就面临着一个设计问题首先。现在,如果你想知道是否有可能只是知道的缘故,或者如果有在地球上,那就没办法了,它的确是可能的,一个非常小的助手库并扩展方法

As other stated, if you need to 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");



使用此代码,你可以只用两个属性的支持字段,并分配新价值的支持字段。你可以阅读有关实施

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

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; }

如果你有一个自定义代码的复杂性,支持字段解析器会失败。

If you have complex properties with custom code, the backing field resolver will fail.

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

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