C# Lambdas and “this” variable scope

后端 未结 3 2120
悲&欢浪女
悲&欢浪女 2021-02-19 17:34

I am wondering whether I can use the this keyword inside a C# lambda, although actually I know that I can but I want to make sure that this isn\'t a bad th

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-19 18:26

    While it is correct to use this in a lambda like that, you just need to be aware that your Repository object will not be garbage collectable until your Person object is garbage collectable.

    You might want to have a field to cache the result from your lambda, and once it is Lazy filled, release the lambda since you do not need it anymore.

    Something like:

    private Lazy nameProxy; 
    private string name;
    public string Name 
    { 
      get 
      {
        if(name==null)
        {
          name = nameProxy.Value;
          nameProxy = null;
        }
        return name;
      } 
    } 
    

提交回复
热议问题