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

后端 未结 7 1966
灰色年华
灰色年华 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:38

    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. :)

提交回复
热议问题