开发者

Does the dynamic keyword in C# 4 permit certain previously impossible operations with generics?

开发者 https://www.devze.com 2022-12-10 01:32 出处:网络
The dynamic keyword in C# 4 introduces new ways to work with objects that weren\'t previously possible. How does this overlap with generics? Specifically, are there operations that would be potentiall

The dynamic keyword in C# 4 introduces new ways to work with objects that weren't previously possible. How does this overlap with generics? Specifically, are there operations that would be potentially useful which are now legal and valid?

For example, this isn't possible now:

// Use a t开发者_JAVA技巧ype whose value is known only at runtime.
Type t = ...;
List<t> l = new List<t>();
// ... (add some items to the list)
t first = l[0];

Is there a way to accomplish something similar once dynamic is available?


dynamic doesn't help you much here. You still need to use Type.GetGenericTypeDefinition()/MakeGenericType() to create the object initially, which is less than pleasant.

If I understand it correctly, what dynamic will do is once you have the type constructed that way, it will make it easier to work with. For example, you know you have a list of some type, even if the compiler doesn't. So if you've assigned that list to a dynamic variable you can do things like call it's .Add() method and the call should resolve at run time.

Note that I haven't played with this yet personally, though, so until you try it yourself this is still just hearsay.


You can do that now, though you have to really want it. Observe:

Type t = ...;
typeof(List<>)
    .MakeGenericType(t)
    .GetMethod(...);

Generics and reflection: not really better together, but if you need it...

0

精彩评论

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