class PriceClass {
private int value;
public int Value
{
get { return this.value; }
set { this.value = value; }
}
}
struct PriceStruct
{
private int value;
public int Value
{
get { return this.value; }
set { this.value = value; }
}
}
static void Main(string[] args)
{
PriceClass _priceClass = new PriceClass();
Type type = typeof(PriceClass);
PropertyInfo info = type.GetProperty("Value");
info.SetValue(_priceClass, 32, null);
Console.WriteLine(_priceClass.Value);
PriceStruct _priceStruct = new PriceStruct();
type = typeof(PriceStruct);
info = type.GetProperty("Value");
info.SetValue(_priceStruct, 32, null);
Console.WriteLine(_priceStruct.Value);
Debugger.Break();
}
打印的第一个值是32,第二个值是0。不会引发异常
最佳答案
这是因为对结构进行装箱会对其进行复制,因此您应该更早对它进行装箱,以便从修改后的相同数据中调用 setter/getter 。以下代码有效:
object _priceStruct = new PriceStruct(); //Box first
type = typeof(PriceStruct);
info = type.GetProperty("Value");
info.SetValue(_priceStruct, 32, null);
Console.WriteLine(((PriceStruct)_priceStruct).Value); //now unbox and get value
Debugger.Break();
关于reflection - 为什么反射不在Struct中设置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6608368/