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

如何在c#中实现选择性属性可见性?,第1张

概述我们可以让一个类的属性可以公开看到,但只能被某些特定的类修改? 例如, // this is the property holderpublic class Child{ public bool IsBeaten { get; set;}}// this is the modifier which can set the property of Child instancepu 我们可以让一个类的属性可以公开看到,但只能被某些特定的类修改?

例如,

// 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{    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 { ... }
总结

以上是内存溢出为你收集整理的如何在c#中实现选择性属性可见性?全部内容,希望文章能够帮你解决如何在c#中实现选择性属性可见性?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1260817.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存