C# return a variable as read only from get; set;

后端 未结 7 2294
不思量自难忘°
不思量自难忘° 2021-02-02 07:30

I swear I have seen an example of this but have been googling for a bit and can not find it.

I have a class that has a reference to an object and need to have a GET; met

7条回答
  •  轮回少年
    2021-02-02 08:06

    If the object isn't too complicated/extensive then write an wrapper around it.

    for example:

    class A {
        public string strField = 'string';
        public int intField = 10;
    }
    
    class AWrapper {
        private A _aObj;
    
        public AWrapper(A aobj) {
          _aObj = A;
        }
    
        public string strField {
             get {
                return _aObj.strField;
             }
        }
    
        public int intField {
             get {
                return _aObj.intField;
             }
        }
    }
    

    So now all you do is give your client code an instance of the AWrapper class so that they may only use what you allow them to see.

    this may get a bit complicated and may not scale well if your base class is not set in stone, but for most simple situation it may just do the trick. I think this is called a facade pattern(but don't quote me on that =) )

提交回复
热议问题