转换为IEnumerable的<动态>?

编程入门 行业动态 更新时间:2024-10-27 12:38:11
本文介绍了转换为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;?

本文发布于:2023-11-26 22:47:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635514.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   动态   LT   IEnumerable   GT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!