简体   繁体   English

属性在C#中使用反射使用getter方法时如何设置值

[英]How set value when the property has the getter method using reflection in c#

public class test
{
    public test()
    {
        ting=10;
    }
    private int ting{get;set;}

    public int tring
    {
        get
        {
            return ting;
        }
    }

}

void Main()
{
    var t= new test();

    //Below line giving error
    Console.Write(t.GetType().GetProperty("tring").SetValue(t,20));
}

How to resolve this using reflection? 如何使用反射解决此问题?

Well yes - the property can't be set. 是的- 无法设置该属性。 It's read-only, presumably deliberately. 它是只读的,大概是故意的。

If the designer of the class hasn't given you the opportunity of setting the value, you shouldn't be trying to set it. 如果班级的设计者没有给您设置值的机会,则不应尝试设置它。 In many cases it would be impossible to do so, as the value may not even be backed by a field (think DateTime.Now ) or may be computed some non-reversible way (as per Marcin's answer). 在许多情况下,这样做是不可能的,因为该值甚至可能没有字段支持(例如DateTime.Now ),或者可能以某种不可逆的方式进行计算(根据Marcin的回答)。

In this particular case if you were really devious you could get hold of the IL implementing tring.get , work out that it's fetching from the ting property, and then call that setter by reflection - but at that point you're going down a very dark path which you're almost certain to regret. 在这种特殊情况下,如果您真的很 tring.get ,则可以掌握实现tring.get的IL,确定它是从ting属性中获取的,然后通过反射调用 setter,但是到那时,您将黑暗的道路,你几乎一定会后悔。

You can't do that, unless you know what is the backing field name. 除非知道后备字段名称是什么,否则您不能这样做。 When you do, you can just set the field value, and it will reflect to property value. 这样做时,您只需设置字段值,它将反映为属性值。

Consider the situation when it would be possible and your property wouldn't be backed by a field (like that): 考虑一下可能的情况,而您的财产将不会得到字段的支持(像这样):

public string tring
{
    get
    {
        return string.format("foo {0} foo", ting);
    }
}

What should be desired output of set ting that property? set该属性所需的输出是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM