类的属性是一个对象,怎么才能使这个对象的属性在外部只能读取,不能赋值?
比如
class A
{
public int Value { get; set; }
}
class B
{
public A Obj { get; private set; }
public B()
{
this.Obj = new A() { Value = 1 };
}
}
class Program
{
static void Main(string[] args)
{
B a = new B();
a.Obj.Value = 2; //怎样才能让这步不被允许?A是dll中的类,不能修改。只能改B和Program。
}
}
------解决方案--------------------------------------------------------
那你就只让他取值,别让它取对象,
class B
{
private A Obj;
public int Value { get; }
public B()
{
this.Obj = new A() { Value = 1 };
}
}
------解决方案--------------------------------------------------------
这个没办法。要么就你再生成个新对象,取得的是新对象,不会修改原来的数据。
class B
{
private A obj;
public A Obj { get { A tem = new A();复制原来的值; return tem; }; }
public B()
{
this.Obj = new A() { Value = 1 };
}
}
------解决方案--------------------------------------------------------
通过反射能大概做到这个,不过就看能不能直观的得到属性名称
class TestClass { public string Name { get; set; } }
class Decorator<T> where T :class
{
private T obj;
public Decorator(T value)
{
this.obj = value;
}
public object GetProperty(string propertyName)
{
System.Reflection.PropertyInfo property = this.obj.GetType().GetProperty(propertyName);