Limiting access to a public setter to specific objects (C#)

前端 未结 6 1339
春和景丽
春和景丽 2021-01-16 09:48

I\'m trying to create a class (in C#) that serves as an environment for my application.

I\'m trying to make the class dynamic, and send it as a parameter to entities

6条回答
  •  情话喂你
    2021-01-16 10:09

    Isn't "internal" sufficient for what you need?

    And you could move the setters into an interface as explicit implementation. Then they are hidden from the public interface and only accessible if you cast to the interface.

    And if you want to make really sure that nobody else can call it you can add some parameter to these functions where you expect a certain token object which you only give to trusted classes.

    void SetX(int value, object token)
    {
        if(token!=correctToken)
            throw new ArgumentException("wrong token");
        x=value;
    }
    

提交回复
热议问题