怎么保护类的对象属性不能在外部被修改?
类的属性是一个对象,怎么才能使这个对象的属性在外部只能读取,不能赋值?
比如
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 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);
if (property != null)
return property.GetValue(obj, null);
else
{
return null;
}
}
}
class Program
{
static void Main(string[] args)
{
TestClass a = new TestClass() { Name = "name1" };
Decorator<TestClass> b = new Decorator<TestClass>(a);
var name = b.GetProperty("Name");
}
}