112

在 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;}
4

12 回答 12

123

不,那里没有。自动实现的属性仅用于实现最基本的属性:带有 getter 和 setter 的支持字段。它不支持这种类型的自定义。

但是您可以使用 4.0Lazy<T>类型来创建此模式

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

此代码将延迟计算_someVariable第一次Value调用表达式的值。它只会计算一次,并将缓存该Value属性的值以供将来使用

于 2010-10-27T19:20:16.867 回答
42

可能最简洁的方法是使用 null-coalescing 运算符:

get { return _SomeVariable ?? (_SomeVariable = SomeClass.IOnlyWantToCallYouOnce()); }
于 2010-10-27T19:23:57.087 回答
18

C#6 中有一个名为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;
}
于 2016-06-29T07:57:42.037 回答
15

运算符??=在 C# 8.0 及更高版本中可用,因此您现在可以更简洁:

private string _someVariable;

public string SomeVariable => _someVariable ??= SomeClass.IOnlyWantToCallYouOnce();

于 2020-07-25T07:39:37.423 回答
5

不是这样,属性的参数值必须是常量,你不能调用代码(即使是静态代码)。

但是,您可以使用 PostSharp 的 Aspects 来实现一些东西。

去看一下:

PostSharp

于 2010-10-27T19:20:31.720 回答
5

这是我解决您问题的方法。基本上,这个想法是一个属性,将在第一次访问时由函数设置,后续访问将产生与第一次相同的返回值。

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());
    } 
}

传递函数指针当然有开销,但它为我完成了这项工作,与一遍又一遍地运行该方法相比,我没有注意到太多的开销。

于 2011-06-26T03:13:33.370 回答
3

我是这个想法的忠实拥护者,并想提供以下 C# 片段,我称之为 proplazy.snippet。(您可以将其导入或将其粘贴到您可以从片段管理器获得的标准文件夹中)

这是它的输出示例:

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

这是片段文件的内容:(另存为proplazy.snippet)

<?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>
于 2018-09-18T18:01:14.277 回答
3

我是这样做的:

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; 
    });
于 2018-10-24T16:05:27.187 回答
2

我认为纯 C# 不可能做到这一点。但是你可以使用像PostSharp这样的 IL 重写器来做到这一点。例如,它允许您根据属性在函数之前和之后添加处理程序。

于 2010-10-27T19:19:53.993 回答
0

https://github.com/bcuff/AutoLazy使用 Fody 给你这样的东西

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);
        }
    }
}
于 2017-06-22T06:38:33.247 回答
0
[Serializable]
public class ReportModel
{
    private readonly Func<ReportConfig> _getReportLayout;
    public ReportModel(Func<ReportConfig> getReportLayout)
    {
        _getReportLayout = getReportLayout;
    }

    private ReportConfig _getReportLayoutResult;
    public ReportConfig GetReportLayoutResult => _getReportLayoutResult ?? (_getReportLayoutResult = _getReportLayout());


    public string ReportSignatureName => GetReportLayoutResult.ReportSignatureName;
    public string ReportSignatureTitle => GetReportLayoutResult.ReportSignatureTitle;
    public byte[] ReportSignature => GetReportLayoutResult.ReportSignature;
}
于 2018-09-12T13:41:31.690 回答
0

如果您在延迟初始化期间使用构造函数,则以下扩展也可能会有所帮助

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>()); */
于 2018-10-28T03:02:32.120 回答