我们可以让一个类的属性公开,但只能被某些特定的类修改吗?如何在c#中实现选择性属性可见性?
例如,
// this is the property holder
public class Child
{
public bool IsBeaten { get; set;}
}
// this is the modifier which can set the property of Child instance
public class Father
{
public void BeatChild(Child c)
{
c.IsBeaten = true; // should be no exception
}
}
// this is the observer which can get the property but cannot set.
public class Cat
{
// I want this method always return false.
public bool TryBeatChild(Child c)
{
try
{
c.IsBeaten = true;
return true;
}
catch (Exception)
{
return false;
}
}
// shoud be ok
public void WatchChild(Child c)
{
if(c.IsBeaten)
{
this.Laugh();
}
}
private void Laugh(){}
}
儿童是一个数据类,
家长是一类可以修改数据,
猫是一个类只能读取数据。
有没有什么办法可以在C#中使用Property实现这种访问控制?
thx。但如果我们无法定义或更改_Beater_,该怎么办?即_Child_代码是客户端代码,而_Beater_可能是一个第三方包,它实现了一些功能,如序列化,后来可以被另一个自由职业取代? – lowatt
在这种情况下,你可能做的并不多。如果Beater的作者定义了它与Child之间的相互作用,那么你可能只需要相信第三方会做正确的事情。这是一个教育和文档问题,而不是代码中可以解决的问题。 –