Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

Restrict use of instance variable to single method in C#

I want to be able to restrict usage of a instance variable to one method, and other usages should not be possible (compile error, or warning). For instance

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
    }
}

Usage of Lazy, automatic properties, or encapsulation in a separate object is not possible. I thought about extending ObsoleteAttribute, but it's sealed.

question from:https://stackoverflow.com/questions/65936053/restrict-use-of-instance-variable-to-single-method-in-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's not a thing that you can do out of the box. You could write a custom Roslyn analyzer that checks, for example, for an attribute of yours and adds a warning/error, but writing Roslyn analyzers is not trivial. It isn't entirely hard, either, note.

Consider:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...