日期:2014-05-17  浏览次数:20904 次

c# 可以利用反射给只读属性赋值吗?
如题。
属性定义如下:
public string Name { get; private set;}

或者
  [ReadOnly(true)]
  public string Name { get; set; }

------解决方案--------------------
可以
C# code

public class Car
{
    private int height;
    [ReadOnly(true)]
    public int Height 
    { 
    get;set;
    }
}

        Car car = new Car();
        car.GetType().GetProperty("Height").SetValue(car, 100,null); //ok

------解决方案--------------------
属性是肯定不可以的。
调用只读属性的SetValue会抛出异常
字段就不知道了。。你可以试试
------解决方案--------------------
探讨

不可以