10

我们可以让一个类的属性对 public 可见,但只能被某些特定的类修改吗?

例如,

// 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(){}
}

Child是数据类,
Parent是可以修改数据的类,
Cat是只能读取数据的类。

有没有办法在 C# 中使用 Property 来实现这种访问控制?

4

2 回答 2

4

您可以提供一个方法,而不是暴露 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 { ... }
于 2012-12-19T06:33:59.280 回答
2

这通常是通过使用单独的程序集和InternalsVisibleToAttribute来实现的。当您在当前程序集中set使用internal类标记时,将可以访问它。通过使用该属性,您可以授予特定的其他程序集对其的访问权限。请记住,通过使用反射,它仍然是可编辑的。

于 2012-12-19T05:17:50.213 回答