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

前端 未结 6 1368
春和景丽
春和景丽 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: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 _protectedObjects = new List();
    
        public MyObject GetItem(int id)
        {
            return (MyObject)_protectedObjects.First(i => i.Id == id).Clone();
        }
    }
    
    public class MyObject : ICloneable
    {
         //[...]
         public object Clone()
         {
             return MemberwiseClone();
         }
    }
    

提交回复
热议问题