转换为IEnumerable的<动态>? [英] Convert to IEnumerable<dynamic>?

查看:143
本文介绍了转换为IEnumerable的<动态>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个扩展方法:

public static class A
{
 public static IEnumerable<dynamic> AsDynamic<T>(this IEnumerable<T> f)
    {
        foreach (var element in f)
        {
                yield return (dynamic) element;
        }   
    }
}

和测试它:

List<int> l   = new List<int>(){1,2,3};
Console.WriteLine ( l.AsDynamic().GetType());

但输出的是:的typeof(IEnumerable的&LT;对象&gt;)

  • 为什么不的typeof(IEnumerable的&LT;动态&GT;)?

我怎样才能使之成为喜欢它?

How can I make it to be like it ?

推荐答案

我觉得你有什么动态误会表示。从本质上讲,当你告诉一个对象的类型是动态,你承诺的对象在运行时将支持任何方法或属性的编译器调用,换来了编译器不抱怨的在编译时。您还保证,你将面临的后果,如果你打破你的承诺。

I think that you have a misunderstanding of what dynamic means. Essentially, when you tell the compiler that an object's type is dynamic, you "promise" that the object at runtime will support whatever methods or properties that you invoke, in exchange for the compiler not complaining at compile time. You also promise that you will face the consequences if you break your promise.

当你说一个对象是动态,编译器不能对类型的假设,所以它使用对象,知道什么都可以存储为对象。当你做出一个的IEnumerable&LT;动态&GT; ,就变成的IEnumerable&LT;对象&gt; ,有一个显著的区别:你可以调用在其元素的任何方法,编译器会不会说一句话:

When you say that an object is dynamic, the compiler cannot make assumptions about the type, so it uses object, knowing that anything can be stored as object. When you make an IEnumerable<dynamic>, it becomes IEnumerable<object>, with one significant difference: you can call any method on its elements, and the compiler will not say a word:

IEnumerable<SomeType> original = ...
foreach (dynamic x in original.AsDynamic()) { // Using your method
    Console.WriteLine(x.SomeUnsupportedMethod()); // The compiler is silent!
}

由于 original.AsDynamic()给出了动态的对象序列,编译器不抱怨你的电话以 SomeUnsupportedMethod 。如果确实不支持在运行时的方法,程序会崩溃;如果该方法是由 SOMETYPE 元素的实际支持,就没有崩溃,而且该方法将被调用。

Since original.AsDynamic() gives a sequence of dynamic objects, the compiler does not complain about your call to SomeUnsupportedMethod. If the method is indeed not supported at runtime, the program will crash; if the method is actually supported by elements of SomeType, there would be no crash, and the method will be invoked.

这是所有的动态会为你做;静态的占位符仍将对象的typeof 会告诉你一样多。但是,对象(其方法和属性)的确切功能不会被检查到运行时。

That's all the dynamic will do for you; statically, the "placeholder" will remain object, and typeof will tell you as much. But the exact capabilities of the object (its methods and properties) will not be examined until runtime.

这篇关于转换为IEnumerable的&LT;动态&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆