【问题标题】:RunTimeBinderException when passing int[] to method having parameter type dynamic将 int[] 传递给具有参数类型动态的方法时出现 RunTimeBinderException
【发布时间】:2018-08-26 08:27:31
【问题描述】:

除非我将GetCount 参数类型从ICollection 更改为dynamic,否则下面的代码工作得很好——它会抛出RuntimrBinderException 为什么在运行时Count 属性不可用?

static void Main(string[] args)
        {
            var list = new int[] { 1, 2, 3 };
            var x = GetCount(list);
            Console.WriteLine(x);
        }
        private static int GetCount(ICollection array) /*changing array type to dynamic fails at runtime*/
        {
            return array.Count;
        }

【问题讨论】:

  • Coz Array 没有 Count 属性。数组具有 Length 属性。试试array.Lengthdynamic
  • @ChetanRanpariya : ICollection
  • 是的.. 因为 ICollection 有 Count 属性。当您使用动态时,Array 不会转换为 ICollection,编译器将尝试使用特定于传递的类型的属性。并且 Array 没有 Count 属性。 stackoverflow.com/questions/4769971/…
  • Array 通过显式接口实现实现 ICollection.Count 属性,这就是 Count 属性不能直接在 Array 上使用的原因。

标签: c# dynamic dynamic-language-runtime


【解决方案1】:

这失败的原因是因为在数组中,尽管它们实现了ICollectionCount 是显式实现的。显式实现的成员只能通过接口类型引用调用。

考虑以下几点:

interface IFoo 
{
    void Frob();
    void Blah();
} 

public class Foo: IFoo
{
     //implicit implementation
     public void Frob() { ... }

     //explicit implementation
     void IFoo.Blah() { ... }
}

现在:

var foo = new Foo();
foo.Frob(); //legal
foo.Blah(); //illegal
var iFoo = foo as IFoo;
iFoo.Blah(); //legal

在您的情况下,当输入参数ICollection 时,Count 是有效的调用,但是当使用dynamic 时,参数不会隐式转换为ICollection,它仍然是int[]并且Count 根本无法通过该引用调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 2021-07-17
    相关资源
    最近更新 更多