C# - 动态类型还是类型转换?
说到性能,C# 有什么更好的地方?使用动态类型还是类型转换?
像这样(只是一个例子,不是真正的实现):
var list = new List<object>();
list.Add(new Woman());
list.Add(new Men());
list.Add(new Car());
....... in another code ....
var men = (Men)list[1];
men.SomeMenMethod();
或者这样
var list = new List<dynamic>();
list.Add(new Woman());
list.Add(new Men());
list.Add(new Car());
....... in another code ....
var men = list[1];
men.SomeMenMethod();
Talking about performance, what is better in C#? Use Dynamic types or Typecast?
Like this (just an example, not the real implementation):
var list = new List<object>();
list.Add(new Woman());
list.Add(new Men());
list.Add(new Car());
....... in another code ....
var men = (Men)list[1];
men.SomeMenMethod();
Or this
var list = new List<dynamic>();
list.Add(new Woman());
list.Add(new Men());
list.Add(new Car());
....... in another code ....
var men = list[1];
men.SomeMenMethod();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该示例是人为设计的,因为您知道 list[1] 是一个
Men
。所以在这种情况下,两者都是相同的。当您不知道确切的类型,但您确实知道在运行时它将具有
SomeMethod
或属性时,动态会变得有用。当然,如果类型假设错误,则第一个会在
var men = (Men)list[1];
行上引发异常,而后者会在men.SomeMenMethod( );
The example is contrived as you know list[1] is a
Men
. So in that case either is identical.Where dynamic becomes useful where you don't know the precise type, but you do know that at runtime that it will have a
SomeMethod
or property.Of course if the type assumption is wrong, then the first throws an exception on the
var men = (Men)list[1];
line while the latter throws the exception onmen.SomeMenMethod();
如果可能的话,两者都不要使用。尝试使用不涉及转换或动态的类型安全解决方案。
如果这是不可能的,则强制转换更好,因为它更清晰,类型更安全(编译器可以检查
Men
实际上确实有SomeMenMethod
),例外情况是错误更清晰,它不会偶然起作用(如果你认为你有Men
,但你实际上有Woman
,它实现了相同的方法,它可以工作,但它是可能是一个错误)。你问的是性能。除了您之外,没有人能够真正了解您的具体案例的表现。如果您真的关心性能,请始终从两个方面进行衡量。
但我的期望是动态会慢得多,因为它必须在运行时使用小型编译器之类的东西。它尝试在第一次运行后缓存结果,但它仍然很可能不会比强制转换更快。
If possible, don't use either. Try to use type-safe solution that doesn't involve casting or
dynamic
.If that's not possible, casting is better, because it's more clear, more type-safe (compiler can check that
Men
actually does haveSomeMenMethod
), the exception in case of an error is clearer and it won't work by accident (if you think you haveMen
, but you actually haveWoman
, which implements the same method, it works, but it's probably a bug).You asked about performance. Nobody other than you can really know the performance of your specific case. If you really care about performance, always measure both ways.
But my expectation is that
dynamic
is going to be much slower, because it has to use something like a mini-compiler at runtime. It tries to cache the results after first run, but it still most likely won't be faster than a cast.