Для получения полного доступа
зарегистрируйтесь

Ленивая инициализация для свойств без создания private переменной для каждого свойства


  public class PropertyStore
  {
      private readonly ConcurrentDictionary<string, object> _dictionary = new ConcurrentDictionary<string, object>();
      public T Get<T>(Func<T> instanceCreator, [CallerMemberName] string propertyName = "")
      {
          _dictionary.GetOrAdd(propertyName, key => instanceCreator());
          return (T)_dictionary[propertyName];
      }

      public void Set<T>(T value, [CallerMemberName] string propertyName = "")
      {
          _dictionary.AddOrUpdate(propertyName, value, (key, oldValue) => value);
      }
  }

Использование:

  public class MyClass
  {
      private readonly PropertyStore _store = new PropertyStore();

      public string MyString
      {
          get => _store.Get(() => "It's my default string");
          set => _store.Set(value);
      }

      public int MyInt
      {
          get => _store.Get(() => 5);
          set => _store.Set(value);
      }

      public SecondClass MySecondClass
      {
          get => _store.Get(() => new SecondClass());
          set => _store.Set(value);
      }
  }

Проверка:

  class Program
  {
      static void Main(string[] args)
      {
          var myClass = new MyClass();

          Console.WriteLine(myClass.MyString); //"It's my default string"
          myClass.MyString = "Custom string";
          Console.WriteLine(myClass.MyString); //Custom string

          Console.WriteLine(myClass.MyInt); //5
          myClass.MyInt = 10;
          Console.WriteLine(myClass.MyInt); //10

          Console.WriteLine(myClass.MySecondClass); //SecondClass Initialized
                                                    //SecondClass

          Console.WriteLine(myClass.MySecondClass); //SecondClass
      }
  }

  public class SecondClass
  {
      public SecondClass()
      {
          Console.WriteLine($"{nameof(SecondClass)} Initialized");
      }

      public override string ToString()
      {
          return nameof(SecondClass);
      }
  }

Другие варианты сниппета Отсортировано по рейтингу


  Рейтинг
0

Ленивая инициализация для свойств без создания private переменной для каждого свойства 21 июля 2017 г., 15:38:51
```csharp public class PropertyStore { private readonly ConcurrentDictionary _dictionary = new ConcurrentDictionary(); public T Get(Func instanceCreator, [CallerMemberName] string propertyName = "") { _dictionary.GetOrAdd(propertyName, key => instanceCreator()); return (T)_dictionary[propertyName]; } public void Set(T value, [CallerMemberName] string propertyName = "") { _dictionary.Adate(propertyName, value, (key, oldValue) => value); } } ``` Использование: ```csharp public class MyClass { private readonly PropertyStore _store = new PropertyStore(); public string MyString { get => _store.Get(() => "It's my default string"); set => _store.Set(value); } public int MyInt { get => _store.Get(() => 5); set => _store.Set(value); } public SecondClass MySecondClass { get => _store.Get(() => new SecondClass()); set => _store.Set(value); } } ``` Проверка: ```csharp class Program { static void Main(string[] args) { var myClass = new MyClass(); Console.WriteLine(myClass.MyString); //"It's my default string" myClass.MyString = "Custom string"; Console.WriteLine(myClass.MyString); //Custom string Console.WriteLine(myClass.MyInt); //5 myClass.MyInt = 10; Console.WriteLine(myClass.MyInt); //10 Console.WriteLine(myClass.MySecondClass); //SecondClass Initialized //SecondClass Console.WriteLine(myClass.MySecondClass); //SecondClass } } public class SecondClass { public SecondClass() { Console.WriteLine($"{nameof(SecondClass)} Initialized"); } public override string ToString() { return nameof(SecondClass); } } ```

Чтобы увидеть комментарии, нужно быть участником сообщества

Регистрация