简体   繁体   中英

C# - Dynamic Type or Typecast?

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();

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM