【发布时间】:2021-05-02 06:51:18
【问题描述】:
我希望能够将实例变量的使用限制为一种方法,而其他用法应该是不可能的(编译错误或警告)。比如
public class Example
{
public string Accessor()
{
if (SuperPrivate == null) // allowed
{
SuperPrivate = "test"; // allowed
}
return SuperPrivate; // allowed
}
private string SuperPrivate;
public void NotAllowed()
{
var b = SuperPrivate.Length; // access not allowed
SuperPrivate = "wrong"; // modification not allowed
}
public void Allowed()
{
var b = Accessor().Length; // allowed
// no setter necessary in this usecase
}
}
不能在单独的对象中使用惰性、自动属性或封装。我想过扩展 ObsoleteAttribute,但它是密封的。
【问题讨论】:
-
你不能。如果你认为你需要这个,我建议你可能已经把自己建模到了一个角落——也许试图通过 C# 类型系统规则来强制执行业务规则?
-
添加一条“不允许写访问”的评论,并谴责任何不遵守此规则的开发者。
-
你为什么要这样做?
-
不仅不允许写访问,所有访问都只允许通过Accessor方法。
-
您能向我们解释一下为什么您想这样做吗?为什么要这样做,而不是将班级分成两个单独的班级?
标签: c# variables methods access-control datamember