中的属性实现此类访问控制
我们可以使公众可见类的属性,但只能通过某些特定类修改?
例如,
// 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(){}
}
儿童是一个数据类,
parent 是可以修改数据的类 CAT 是只能读取数据的类。
有什么方法可以使用C#?
而不是揭露儿童类的内在状态,您可以提供一种方法:
class Child {
public bool IsBeaten { get; private set; }
public void Beat(Father beater) {
IsBeaten = true;
}
}
class Father {
public void BeatChild(Child child) {
child.Beat(this);
}
}
然后猫无法击败你的孩子:
class Cat {
public void BeatChild(Child child) {
child.Beat(this); // Does not compile!
}
}
如果其他人需要击败孩子,请定义可以实现的接口:
interface IChildBeater { }
然后让他们实现它:
class Child {
public bool IsBeaten { get; private set; }
public void Beat(IChildBeater beater) {
IsBeaten = true;
}
}
class Mother : IChildBeater { ... }
class Father : IChildBeater { ... }
class BullyFromDownTheStreet : IChildBeater { ... }
通常是通过使用单独的组件和内部visibletoatibute来实现的。当您在当前组件中使用internal
类标记set
时,将可以访问它。通过使用该属性,您可以让特定的其他程序集访问它。请记住,通过使用反射,它仍然总是可以编辑的。