C# - 动态类型还是类型转换?

发布于 2024-12-02 00:44:18 字数 479 浏览 0 评论 0原文

说到性能,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凝望流年 2024-12-09 00:44:18

该示例是人为设计的,因为您知道 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 on men.SomeMenMethod();

○闲身 2024-12-09 00:44:18

如果可能的话,两者都不要使用。尝试使用不涉及转换或动态的类型安全解决方案。

如果这是不可能的,则强制转换更好,因为它更清晰,类型更安全(编译器可以检查 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 have SomeMenMethod), the exception in case of an error is clearer and it won't work by accident (if you think you have Men, but you actually have Woman, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文