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

后端 未结 7 1168
忘了有多久 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

  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 16:45

    You could implement lazy initialization in a manner similar to this:

      public class Lazy where T : new()
           private T _value;
           private bool _isInitialized;
           private T GetValue()
               if (!_isInitialized)
                   _value = new T();
                   _isInitialized = true;
               return _value;
           public static implicit operator T (Lazy t)
               return t.GetValue();

    which would allow you to write code like this:

          private Lazy _lazyCt = new Lazy();
          public ComplexType LazyCt
              get { return _lazyCt; }

    The specifics of the initialization are irrelevant, I wrote it like this to show that you can make it transparently convertible to the non-lazy version, and perform the initialization on the first conversion. :)