C# Equivalent for C++ Macros and using Auto<> Properties

后端 未结 7 1906
灰色年华
灰色年华 2021-02-20 16:35

I have some auto-instantiation code which I would like to apply to about 15 properties in a fairly big class. The code is similar to the following but the type is differ

7条回答
  •  孤街浪徒
    2021-02-20 16:47

    You can make a generic struct that handles the lazy creation:

    public struct LazyCreate where T : class, new() {
       private T _value;
       public T Value {
          get {
             if (_value == null) {
                _value = new T();
             }
             return _value;
          }
       }
    }
    
    protected LazyCreate _propertyName;
    public ComplexType PropertyName {
        get {
            return _propertyName.Value;
        }
    }
    

提交回复
热议问题