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

MrZ*_*arq 2 c# variables methods access-control datamember

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

无法使用惰性、自动属性或封装在单独的对象中。我考虑过扩展 ObsoleteAttribute,但它是密封的。

Mar*_*ell 5

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

考虑:

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