扩展方法和动态对象 [英] Extension method and dynamic object

查看:86
本文介绍了扩展方法和动态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要总结一下我的问题分为以下code片段。

I am going to summarize my problem into the following code snippet.

List<int> list = new List<int>() { 5, 56, 2, 4, 63, 2 };
Console.WriteLine(list.First());

以上code是工作的罚款。

Above code is working fine.

现在我尝试以下

dynamic dList = list;
 Console.WriteLine(dList.First());

但我正在逐渐RuntimeBinderException.Why会这样呢?

but I am getting RuntimeBinderException.Why is it so?

推荐答案

要扩大Stecya的答案...扩展方法,并没有以扩展方法的形式动态类型的支持的,即所谓的如同它们是实例方法。然而,这将工作:

To expand on Stecya's answer... extension methods aren't supported by dynamic typing in the form of extension methods, i.e. called as if they were instance methods. However, this will work:

dynamic dList = list;
Console.WriteLine(Enumerable.First(dList));

当然,这可能会或可能不会是有用的。如果你能提供有关为什么和怎样你要使用动态类型的更多信息,我们也许能够帮助更多的。

Of course, that may or may not be useful. If you could give more information about why and how you're trying to use dynamic typing, we may be able to help more.

这篇关于扩展方法和动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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