In a non-static method I could use this.GetType()
and it would return the Type
. How can I get the same Type
in a static method? Of course, I can't just write typeof(ThisTypeName)
because ThisTypeName
is known only in runtime. Thanks!
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
For my purposes, I like @T-moty's idea. Even though I have used "self-referencing type" information for years, referencing the base class is harder to do later.
For example (using @Rob Leclerc example from above):
Working with this pattern can be challenging, for example; how do you return the base class from a function call?
Or when type casting?
So, I try to avoid it when I can, and use it when I must. If you must, I would suggest that you follow this pattern:
Now you can (more) easily work with the
BaseClass
. However, there are times, like my current situation, where exposing the derived class, from within the base class, isn't needed and using @M-moty's suggestion just might be the right approach.However, using @M-moty's code only works as long as the base class doesn't contain any instance constructors in the call stack. Unfortunately my base classes do use instance constructors.
Therefore, here's my extension method that take into account base class 'instance' constructors:
EDIT This methods will works only when you deploy PDB files with the executable/library, as markmnl pointed out to me.
Otherwise will be a huge issue to be detected: works well in developement, but maybe not in production.
Utility method, simply call the method when you need, from every place of your code: