如何在c#中实现选择性属性可见性?

如何在c#中实现选择性属性可见性?,c#,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

我们是否可以使类的属性对公众可见,但只能由某些特定类修改

比如说,

// 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(){}
}
子类是一个数据类,
父类是一个可以修改数据的类,
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 { ... }

谢谢。但是如果我们不能定义或改变打浆机呢?i、 子代码是客户机代码,而Beater可能是第三方包,它实现了一些功能,比如序列化,以后可以被另一个库替换?在这种情况下,您可能做不了多少。如果Beater的作者定义了它和孩子之间的互动,你可能只需要相信第三方会做正确的事情。这更像是一个教育和文档问题,而不是可以用代码解决的问题。