读书人

如何保护类的对象属性不能在外部被修改

发布时间: 2013-02-24 17:58:56 作者: rapoo

怎么保护类的对象属性不能在外部被修改?
类的属性是一个对象,怎么才能使这个对象的属性在外部只能读取,不能赋值?
比如

    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);


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");
}
}

读书人网 >C#

热点推荐