Count number of objects of class type within class method

前端 未结 4 1480
北恋
北恋 2021-01-16 04:43

How can I count the number of objects of a class type within a method of that class? For that matter, how to do it outside of a class without adding the objects to a list?

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-16 05:18

    I'm not exactly sure what you mean. But it might be this:

    MethodInfo methodInfo = ...;
    MethodBody body = methodInfo.GetMethodBody();
    int count = body.LocalVariables.Count(variable => variable.LocalType == typeof(DesiredType));
    

    Another possibility: The profiler in Team Suite (and maybe others) can tell you:

    • The number of objects of type T allocated in every method
    • The number of bytes allocated in each method

    Edit: Due to the lack of a "dup n" or "swap n, n+1" IL instruction, the compiler is forced to generate locals you might not expect (ones you didn't explicitly declare). The compiler is also free to remove locals where possible when optimization is on.

提交回复
热议问题