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));
}
如何使用反射来解决这个问题?
发布于 2013-04-07 16:21:46
是的,这个属性不能被设置。它是只读的,可能是故意的。
如果类的设计者没有给你设置值的机会,你就不应该尝试设置它。在许多情况下,这样做是不可能的,因为值可能甚至不是由字段支持的(比如DateTime.Now
),或者可能是以某种不可逆的方式计算的(根据Marcin的答案)。
在这种情况下,如果你真的不小心,你可以获得实现tring.get
的IL,计算出它是从ting
属性获取的,然后通过反射调用那个setter --但在这一点上,你走上了一条非常黑暗的道路,你几乎肯定会后悔的。
发布于 2013-04-07 16:22:02
您不能这样做,除非您知道支持字段的名称。当你这样做的时候,你可以只设置字段的值,它会反映到属性值。
考虑这样一种情况,当它是可能的,并且你的属性不会被字段支持时(就像这样):
public string tring
{
get
{
return string.format("foo {0} foo", ting);
}
}
set
对该属性的期望输出应该是什么?
https://stackoverflow.com/questions/15860309
复制相似问题