c# - Creating a custom property class for multiple re-use within a class -


suppose have c# class has multiple properties this:

private bool _var1dirty = true; private double? _var1; public double? var1 {         {         if (_var1dirty)         {             _var1 = method_var1();             _var1dirty = false;         }         return _var1;     } } 

and differences between each of these properties be:

  1. the type of return var (in case double?, int, string, etc)
  2. the method call - method_var1() (each property have different one)

is there way write custom class?

something along lines of:

public class prop {     public delegate t func();      private bool _dirty = true;     private t _val;     public t val     {                 {             if (_dirty)             {                 _val = func;                 _dirty = false;             }             return _val;         }     } } 

and pass the:

  1. return type t
  2. method func

(ps - know won't compile / dead wrong, wanted give idea of i'm looking for)

any / guidance appreciated.

thanks!!!

you're close. can along lines of this:

public class dirty<t> {     public dirty(func<t> valuefactory)     {         this.valuefactory = valuefactory;         dirty = true;     }      private func<t> valuefactory;     private bool dirty;     private t value;      public t value     {                 {             if (dirty)             {                 value = valuefactory();                 dirty = false;             }              return value;         }     } } 

and consume this:

dirty<double?> dirtydouble = new dirty<double?>(() => somethingthatreturnsadouble()); double? value = dirtydouble.value; 

i'm not sure dirty checking does, if need more complicated bool can turn func<t> checks dirtiness.

edit:

given @mikez comment , answer, can save creation of dirty<t> class using built in lazy<t>, guarantess thread safety:

public class f {     private lazy<double?> lazydouble = new lazy<double?>(() =>                                             methodthatreturnsnullabledouble(), true);     public double? value      {                   {             return lazydouble.value;         }     } } 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -