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 资料的方法
If you're looking for a 1 liner that is equivalent to
this.GetType()
for static methods, try the following.Although this is likely much more expensive than just using
typeof(TheTypeName)
.There's something that the other answers haven't quite clarified, and which is relevant to your idea of the type only being available at execution time.
If you use a derived type to execute a static member, the real type name is omitted in the binary. So for example, compile this code:
Now use ildasm on it... you'll see that the call is emitted like this:
The compiler has resolved the call to
Encoding.GetEncoding
- there's no trace ofUnicodeEncoding
left. That makes your idea of "the current type" nonsensical, I'm afraid.I don't understand why you cannot use typeof(ThisTypeName). If this is a non-generic type, then this should work:
If it's a generic type, then:
Am I missing something obvious here?
When your member is static, you will always know what type it is part of at runtime. In this case:
You cannot call (edit: apparently, you can, see comment below, but you would still be calling into A):
because the member is static, it does not play part in inheritance scenarios. Ergo, you always know that the type is A.
Another solution is to use a selfreferecing type
Then in the class that inherits it, I make a self referencing type:
Now the call type typeof(TSelfReferenceType) inside Parent will get and return the Type of the caller without the need of an instance.
-Rob
You can't use
this
in a static method, so that's not possible directly. However, if you need the type of some object, just callGetType
on it and make thethis
instance a parameter that you have to pass, e.g.:This seems like a poor design, though. Are you sure that you really need to get the type of the instance itself inside of its own static method? That seems a little bizarre. Why not just use an instance method?