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

前端 未结 6 1341
春和景丽
春和景丽 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 09:50

    You could try using Friend assemblies. That will allow only the assemblies you specify to have access to your privates (snicker).

    0 讨论(0)
  • 2021-01-16 10:04

    How about

    class Callee
    {
        public void SetX(TypeOfCaller caller, int value)
        {
        }
    }
    class TypeOfCaller
    {
        public void Do()
        {
            Callee instance;
            //..
            instance.SetX(this, 5);
        }
    }
    

    Doing so; you can also use Visual Studio' Find References feature! In case you want multiple types of caller; you can either opt for class hierarchy or can simply have required overloads

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2021-01-16 10:11

    Maybe i understood something not quite well, but i think Jon had a quite similar problem which he described here. Maybe this can help you.

    0 讨论(0)
  • 2021-01-16 10:14

    You could create a proxy, and send that proxy to your entity classes.

    class MyClass
    {
        public int MyProperty { get; set; }
    }
    
    class MyProxyClass
    {
        public MyProxyClass(MyClass myClass)
        {
            _myClass = myClass;
        }
    
        private MyClass _myClass;
    
        public int MyProperty
        {
            get { return _myClass.MyProperty; }
        }
    }
    
    0 讨论(0)
  • 2021-01-16 10:15

    Why not return clones of your protected objects instead of the actual objects? Solves the problem without adding any more complexity.

    public class MyService
    {
        private List<MyObject> _protectedObjects = new List<MyObject>();
    
        public MyObject GetItem(int id)
        {
            return (MyObject)_protectedObjects.First(i => i.Id == id).Clone();
        }
    }
    
    public class MyObject : ICloneable
    {
         //[...]
         public object Clone()
         {
             return MemberwiseClone();
         }
    }
    
    0 讨论(0)
提交回复
热议问题