C# Lambdas and “this” variable scope

后端 未结 3 2056
悲&欢浪女
悲&欢浪女 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:03

    It is absolutelly fine to use this in lambdas, but there is some stuff you should keep in mind:

    • this will be kept in memory until the lambda is not used anymore
    • if you do not pass lambda "with this" outside your class, then you will not face problems
    • if you do pass lambda "with this" outside your class, then you should remember, that your class will not be collected by the GC until there are references to the lambda left.

    And related to your use-case, you should keep in mind that the Repository instance will never be collected by the GC until people it created are in use.

提交回复
热议问题