【问题标题】:Restrict use of instance variable to single method in C#将实例变量的使用限制为 C# 中的单个方法
【发布时间】: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


【解决方案1】:

这不是你可以开箱即用的事情。您可以编写一个自定义的 Roslyn 分析器,例如检查您的属性并添加警告/错误,但编写 Roslyn 分析器并非易事。请注意,这也不完全困难。

考虑:

// TODO: add an analyzer that checks for this attribute and applies the enforcement
[RestrictAccessTo(nameof(Accessor), nameof(Allowed))]
private string SuperPrivate;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2014-10-16
    • 2011-11-30
    相关资源
    最近更新 更多