专门化一个通用变量
我有一个通用方法,我想为 Strings
做一些特殊的事情。
我发现 DirectCast(DirectCast(value, Object), String)
来获取 String
值(当我已经确认 GetType(T) Is GetType (String)
) 和 DirectCast(DirectCast(newvalue, Object), T)
正如许多类似问题的答案中提到的那样。
但有没有更优雅、更高效的东西呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种特殊情况下,有一个更简单的选项:对值调用
ToString()
。对于字符串,这将仅返回原始引用。在一般情况下,您确实需要向上转换为对象,然后再次向下转换,不幸的是,这非常难看。就性能而言,我会非常惊讶地发现这无论如何都是瓶颈 - 但我怀疑
ToString()
调用与其他任何调用一样高效。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.现在,我实际上已经使用 Reflector 分析了代码(但实际上只关心 ILDASM 输出的等效项 - 事实上,C# 和 VB.NET 渲染器不会在任一方向显示到对象的转换):
DirectCast (DirectCast(value, Object), String)
被编译为,但
DirectCast(DirectCast(newvalue, Object), T)
被编译为所以我对此感到满意(因为我真的只关心选角回到T,正如我在对乔恩·斯基特的回答的评论中所说的那样)。
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 tobut
DirectCast(DirectCast(newvalue, Object), T)
is compiled toSo 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).