将实例变量的使用限制为 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 分析器,例如检查您的属性并添加警告/错误,但编写 Roslyn 分析器并非易事。注意,这也不是很难。

考虑:

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