在 C# 中将实例变量的使用限制为单个方法

Restrict use of instance variable to single method in C#

我希望能够将实例变量的使用限制在一种方法中,并且其他用法应该是不可能的(编译错误或警告)。例如

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,但它是密封的。

这不是开箱即用的事情。您可以编写自定义 Roslyn 分析器来检查您的属性并添加 warning/error,但编写 Roslyn 分析器并不简单。这也不完全困难,请注意。

考虑:

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