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

后端 未结 7 2361
忘了有多久
忘了有多久 2021-02-20 15:55

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:39

    You can use the ?? operator to simplify the code into one line:

    protected ComplexType _propertyName;
    public ComplexType PropertyName
    {
      get
      {
        return _propertyName ?? (_propertyName = new ComplexType());
      }
    }
    

    As a side note I would probably avoid protected fields. If you need to set the property from a derived class I would rather create a protected setter.

提交回复
热议问题