代码之家  ›  专栏  ›  技术社区  ›  ctorx

c延迟加载的自动属性

  •  82
  • ctorx  · 技术社区  · 15 年前

    在C,

    有没有一种方法可以将自动属性转换为具有指定默认值的延迟加载自动属性?

    从本质上讲,我是想把这个……

    private string _SomeVariable
    
    public string SomeVariable
    {
         get
         {
              if(_SomeVariable == null)
              {
                 _SomeVariable = SomeClass.IOnlyWantToCallYouOnce();
              }
    
              return _SomeVariable;
         }
    }
    

    在不同的地方,我可以指定默认值,它自动处理其余的…

    [SetUsing(SomeClass.IOnlyWantToCallYouOnce())]
    public string SomeVariable {get; private set;}
    
    11 回复  |  直到 7 年前
        1
  •  96
  •   Colonel Panic    8 年前

    Lazy<T>

    private Lazy<string> _someVariable =new Lazy<string>(SomeClass.IOnlyWantToCallYouOnce);
    public string SomeVariable => _someVariable.Value;
    

    _someVariable Value

        2
  •  27
  •   redent84    12 年前

    get { return _SomeVariable ?? (_SomeVariable = SomeClass.IOnlyWantToCallYouOnce()); }
    
        3
  •  12
  •   Alexander Derck    10 年前

    Expression Bodied Auto-Properties

    public class SomeClass
    { 
       private Lazy<string> _someVariable = new Lazy<string>(SomeClass.IOnlyWantToCallYouOnce);
    
       public string SomeVariable 
       {
          get { return _someVariable.Value; }
       }
    }
    

    public class SomeClass
    {
       private Lazy<string> _someVariable = new Lazy<string>(SomeClass.IOnlyWantToCallYouOnce);
    
       public string SomeVariable => _someVariable.Value;
    }
    
        4
  •  5
  •   Aren    15 年前
        5
  •  5
  •   Daniel Wolf deepee1    11 年前

    public class LazyProperty<T>
    {
        bool _initialized = false;
        T _result;
    
        public T Value(Func<T> fn)
        {
            if (!_initialized)
            {
                _result = fn();
                _initialized = true;
            }
            return _result;
        }
     }
    

    LazyProperty<Color> _eyeColor = new LazyProperty<Color>();
    public Color EyeColor
    { 
        get 
        {
            return _eyeColor.Value(() => SomeCPUHungryMethod());
        } 
    }
    

        6
  •  3
  •   Zephryl    8 年前

    private Lazy<int> myProperty = new Lazy<int>(()=>1);
    public int MyProperty { get { return myProperty.Value; } }
    

    <?xml version="1.0" encoding="utf-8" ?>
    <CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
        <CodeSnippet Format="1.0.0">
            <Header>
                <Title>proplazy</Title>
                <Shortcut>proplazy</Shortcut>
                <Description>Code snippet for property and backing field</Description>
                <Author>Microsoft Corporation</Author>
                <SnippetTypes>
                    <SnippetType>Expansion</SnippetType>
                </SnippetTypes>
            </Header>
            <Snippet>
                <Declarations>
                    <Literal>
                        <ID>type</ID>
                        <ToolTip>Property type</ToolTip>
                        <Default>int</Default>
                    </Literal>
                    <Literal>
                        <ID>field</ID>
                        <ToolTip>The variable backing this property</ToolTip>
                        <Default>myVar</Default>
                    </Literal>
                    <Literal>
                        <ID>func</ID>
                        <ToolTip>The function providing the lazy value</ToolTip>
                    </Literal>
                    <Literal>
                        <ID>property</ID>
                        <ToolTip>Property name</ToolTip>
                        <Default>MyProperty</Default>
                    </Literal>
    
                </Declarations>
                <Code Language="csharp"><![CDATA[private Lazy<$type$> $field$ = new Lazy<$type$>($func$);
                public $type$ $property$ { get{ return $field$.Value; } }
                $end$]]>
                </Code>
            </Snippet>
        </CodeSnippet>
    </CodeSnippets>
    
        7
  •  2
  •   CodesInChaos    15 年前
        8
  •  0
  •   Sam    9 年前

    https://github.com/bcuff/AutoLazy

    public class MyClass
    {
        // This would work as a method, e.g. GetSettings(), as well.
        [Lazy]
        public static Settings Settings
        {
            get
            {
                using (var fs = File.Open("settings.xml", FileMode.Open))
                {
                    var serializer = new XmlSerializer(typeof(Settings));
                    return (Settings)serializer.Deserialize(fs);
                }
            }
        }
    
        [Lazy]
        public static Settings GetSettingsFile(string fileName)
        {
            using (var fs = File.Open(fileName, FileMode.Open))
            {
                var serializer = new XmlSerializer(typeof(Settings));
                return (Settings)serializer.Deserialize(fs);
            }
        }
    }
    
        9
  •  0
  •   hellow Adolfo Casari    8 年前
    [Serializable]
    public class RaporImza
    {
        private readonly Func<ReportConfig> _getReportLayout;
        public RaporImza(Func<ReportConfig> getReportLayout)
        {
            _getReportLayout = getReportLayout;
        }
    
        private ReportConfig _getReportLayoutResult;
        public ReportConfig GetReportLayoutResult => _getReportLayoutResult ?? (_getReportLayoutResult = _getReportLayout());
    
        public string ImzaAtanKisiAdi => GetReportLayoutResult.ReportSignatureName;
    
        public string ImzaAtanKisiUnvani => GetReportLayoutResult.ReportSignatureTitle;
        public byte[] Imza => GetReportLayoutResult.ReportSignature;
    }
    

    result.RaporBilgisi = new ExchangeProgramPersonAllDataModel.RaporImza(() => _reportConfigService.GetReportLayout(documentTypeId));
    
        10
  •  0
  •   Alexander Zuban    7 年前

    public static class LazyCachableGetter
    {
        private static ConditionalWeakTable<object, IDictionary<string, object>> Instances = new ConditionalWeakTable<object, IDictionary<string, object>>();
        public static R LazyValue<T, R>(this T obj, Func<R> factory, [CallerMemberName] string prop = "")
        {
            R result = default(R);
            if (!ReferenceEquals(obj, null))
            {
                if (!Instances.TryGetValue(obj, out var cache))
                {
                    cache = new ConcurrentDictionary<string, object>();
                    Instances.Add(obj, cache);
    
                }
    
    
                if (!cache.TryGetValue(prop, out var cached))
                {
                    cache[prop] = (result = factory());
                }
                else
                {
                    result = (R)cached;
                }
    
            }
            return result;
        }
    }
    

           public virtual bool SomeProperty => this.LazyValue(() =>
        {
            return true; 
        });
    
        11
  •  0
  •   Makeman    7 年前

    public static partial class New
    {
        public static T Lazy<T>(ref T o) where T : class, new() => o ?? (o = new T());
        public static T Lazy<T>(ref T o, params object[] args) where T : class, new() =>
                o ?? (o = (T) Activator.CreateInstance(typeof(T), args));
    }
    

        private Dictionary<string, object> _cache;
    
        public Dictionary<string, object> Cache => New.Lazy(ref _cache);
    
                        /* _cache ?? (_cache = new Dictionary<string, object>()); */