If I am to use the result of the C# typeof call on the开发者_如何学编程 same type, is it worth saving the value, or just call typeof() multiple times. To me, multiple typeof's are preferable as it can more concise, readable code. I guess it depends on whether the compiler would 'inline' the code?
No, typeof()
is a compile-time keyword.
There could be a small benefit in keeping result of object.GetType()
in a Type
variable.
Update
Type t = typeof(string);
This is what this line is compiled to
IL_0000: nop
IL_0001: ldtoken [mscorlib]System.String
IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
IL_000b: stloc.0
IL_000c: ldloc.0
So internally, it will use GetTypeFromHandle
which I imagine handle here is a pointer to the location of type in the heap.
So there can be a tiny little benefit in calling it once and keeping the reference, although will be minuscule.
精彩评论