C# 如何在大量属性上实现延迟加载

C# 如何在大量属性上实现延迟加载,c#,generics,optimization,lazy-loading,solution,C#,Generics,Optimization,Lazy Loading,Solution,我有一个具有多个属性代码的类,如以下代码段: IFoo a; public IFoo Foo { get { if (a == null) { // load a ... } return a; } } IBar b; public IBar Bar { get { if (b == null) {

我有一个具有多个属性代码的类,如以下代码段:

IFoo a;
public IFoo Foo
{
    get
    {
        if (a == null)
        {
            // load a
            ...
        }
        return a;
    }
}


IBar b;
public IBar Bar
{
    get
    {
        if (b == null)
        {
            // load b
            ...
        }
        return b;
    }
}
我有20多个属性,其中的接口总是不同的,而不是加载结构。 我觉得这个代码不是最优的

有更好的解决办法吗?可能是通用的,例如(不工作):

tb;
公共酒吧
{
得到
{
如果(b==null)
{
//负载b
...
}
返回b;
}
}
尝试使用构造,它实际上是代码的语法糖

来自MSDN的示例(定义如何在构造函数中延迟加载对象a Func,线程安全):


您正在寻找的是一个实现

有一些常用的方法来实现它,比如:虚拟代理、值持有者和Ghost。 正如@bjeger所提到的,您可以使用Lazy来解决您的问题,但是查看并研究上述实现将让您知道什么更适合您的具体情况

下面是一些使用C#::的示例。

使用:


获取较短属性的一种方法至少是惰性的:

Lazy b=newlazy();
公共IBar酒吧
{
得到
{
返回b.值;
}
}

第一次调用b.Value时,它将调用IBar的默认构造函数。有多个重载与线程安全和调用其他构造函数有关。请参阅:

在调用属性getter而不是在实例化时加载有什么原因吗?@JonB这叫做延迟加载。我认为这并不能解决我的问题。我对这些解决方案有多个代码,例如20个属性=20个代码片段。
T b;
public T Bar<T>
{
    get
    {
        if (b == null)
        {
            // load b
            ...
        }
        return b;
    }
}
lazyLargeObject = new Lazy<LargeObject>(() => 
{
    LargeObject large = new LargeObject(Thread.CurrentThread.ManagedThreadId);
    // Perform additional initialization here. 
    return large;
});
LargeObject large = lazyLargeObject.Value;
using System.Threading;

IFoo a;
public IFoo Foo
{
    get
    {
        return LazyInitializer.EnsureInitialized(ref a, () => { /* load a */ });
    } 
}
Lazy<IBar> b = new Lazy<IBar>();
public IBar Bar
{
  get
  {
    return b.Value;
  }
}