开发者

Specialize a generic variable

开发者 https://www.devze.com 2023-01-08 23:37 出处:网络
I have a generic method where I want to do something special for Strings. I\'ve found DirectCast(DirectCast(value, Object), String) to get the String value (when I\'ve already confirmed GetType(T) Is

I have a generic method where I want to do something special for Strings.

I've found DirectCast(DirectCast(value, Object), String) to get the String value (when I've already confirmed GetType(T) Is GetType(String)) and DirectCast(DirectCast(newvalue, Object), T) as mentioned in开发者_开发技巧 a number of answers to similar questions works.

But is there anything more elegant and is it performant?


There's one simpler option in this particular case: call ToString() on the value. For a string, this will just return the original reference.

In the general case, you do need to convert up to object and down again, which is unfortunately pretty ugly. In terms of performance, I'd be pretty surprised to find that this is the bottleneck anyway - but I suspect the ToString() call is as efficient as anything else.


I've now actually analysed the code with Reflector (but really only cared about the equivalent of the ILDASM output -- in fact the C# and VB.NET renderer doesn't display the cast to object in either direction):

DirectCast(DirectCast(value, Object), String) is compiled to

 box !!T
 castclass string

but DirectCast(DirectCast(newvalue, Object), T) is compiled to

 unbox.any !!T

So I am happy with that (seeing as I really only cared about the casting back to T, as I said in my comment to Jon Skeet's answer).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号