加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 03:47:46 所属栏目:百科 来源:网络整理
导读:我们可以让一个类的属性可以公开看到,但只能被某些特定的类修改? 例如, // this is the property holderpublic class Child{ public bool IsBeaten { get; set;}}// this is the modifier which can set the property of Child instancepublic class Father
我们可以让一个类的属性可以公开看到,但只能被某些特定的类修改?

例如,

// 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实现这种访问控制?

解决方法

而不是暴露Child类的内部状态,而是可以提供一个方法:
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 { ... }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读