【问题标题】:How to use lazy with instance variable如何在实例变量中使用惰性
【发布时间】:2013-05-17 15:37:25
【问题描述】:

给定下面的代码

public class classA
{
   int someid ;
   public classA( int x ) { someid = x; }

   Lazy<myType> lazymt1 = new Lazy<myType>( 
       return MyStaticClassMethod.GetFor( someid );    // problem statement - how should this be coded ?
   );

  public myType GetMyType { return lazymt1.value ; }
}

如何传递变量someid 并编码Func&lt;myType&gt;

更新 - 这是我迄今为止尝试过的和结果

Lazy<myType> lazymt1 = new Lazy<myType>( () =>  MyStaticClassMethod.GetFor( someid ) );

上面的行没有编译,红色的波浪线表示

无法将 lambda 表达式转换为 LazyThreadSafetyMode,因为它不是委托类型

【问题讨论】:

    标签: c# .net visual-studio-2012 lazy-loading lazy-evaluation


    【解决方案1】:

    最简单的可能是通过 lambda:

    Lazy<myType> lazymt1 = new Lazy<myType>( 
           () => MyStaticClassMethod.GetFor( someid )
       );
    

    您还需要在构造函数中初始化 Lazy 对象以访问隐式对象引用:

    private Lazy<myType> lazymt1;
    
    public classA()
    {
        lazymt1 = new Lazy<myType>(() => MyStaticClassMethod.GetFor(someid));
    }
    

    【讨论】:

    • @Kumar 好吧,您需要提供有关您用于解决问题的代码的更多信息,因为在这里使用 lambda 的想法根本不是问题。
    • @Kumar 我看到了。我的问题是成立的。你没有表现出足够的能力来复制这个问题。如果GetForMyStaticClassMethod 的方法,它接受int 并返回myType,那么这将起作用。如果不是,那是你的问题,我们不知道它是什么。
    • @Kumar 然后将其移动到构造函数中。您列出的错误表明完全不同的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多