2013-04-10 61 views
18

說,我有一個類,美孚,看起來像這樣:「System.Collections.Generic.IList <object>」不包含「添加」定義「動態」和「ExpandoObject」

public class Foo : IFoo 
{ 
    public Foo() 
    { 
     Bars = new List<dynamic>(); 
    } 
    public IList<dynamic> Bars { get; set; } 
} 

接口IFoo的樣子:

public interface IFoo 
{ 
    IList<dynamic> Bars { get; set; } 
} 

現在,當我做到以下幾點:

IFoo foo = new Foo(); 
dynamic a = new System.Dynamic.ExpandoObject(); 
a.Prop = 10000; 
dynamic b = new System.Dynamic.ExpandoObject(); 
b.Prop = "Some Text"; 
foo.Bars.Add(a); // Throws an 'System.Collections.Generic.IList<object>' does not contain a definition for 'Add' - exception!!!!! 
foo.Bars.Add(b); // Same here!!!!! 

我是什麼在這裏做錯了嗎?

+1

可能重複(http://stackoverflow.com/questions/7996491/cant-understand-the-exception-when- using-dynamic-with-generic-collection-in-ne) – 2013-04-10 10:10:05

+0

你會發布你得到的異常嗎? – 2013-04-11 13:16:15

回答

21

這是一個已知的動態綁定issue

以下是一些變通方法。

使用ICollection<dynamic>代替:

void Main() 
{ 
    IFoo foo = new Foo(); 
    dynamic a = new System.Dynamic.ExpandoObject(); 
    a.Prop = 10000; 
    dynamic b = new System.Dynamic.ExpandoObject(); 
    b.Prop = "Some Text"; 
    foo.Bars.Add(a); 
    foo.Bars.Add(b); 
} 

public interface IFoo 
{ 
    ICollection<dynamic> Bars { get; set; } 
} 

public class Foo : IFoo 
{ 
    public Foo() 
    { 
     Bars = new List<dynamic>(); 
    } 

    public ICollection<dynamic> Bars { get; set; } 
} 

還是直線上升List<dynamic>

public interface IFoo 
{ 
    List<dynamic> Bars { get; set; } 
} 

public class Foo : IFoo 
{ 
    public Foo() 
    { 
     Bars = new List<dynamic>(); 
    } 

    public List<dynamic> Bars { get; set; } 
} 

或者使用dynamic foo

void Main() 
{ 
    dynamic foo = new Foo(); 
    dynamic a = new System.Dynamic.ExpandoObject(); 
    a.Prop = 10000; 
    dynamic b = new System.Dynamic.ExpandoObject(); 
    b.Prop = "Some Text"; 
    foo.Bars.Add(a); 
    foo.Bars.Add(b); 
} 

還是不動綁定add,通過轉換成object

void Main() 
{ 
    IFoo foo = new Foo(); 
    dynamic a = new System.Dynamic.ExpandoObject(); 
    a.Prop = 10000; 
    dynamic b = new System.Dynamic.ExpandoObject(); 
    b.Prop = "Some Text"; 
    foo.Bars.Add((object)a); 
    foo.Bars.Add((object)b); 
} 

或使用像我即興接口第三方框架,ActLike & Prototype Builder Syntax(中的NuGet)更有表現。

void Main() 
{ 
    dynamic New = Builder.New<ExpandoObject>(); 

    IFoo foo = Impromptu.ActLike(
        New.Foo(
         Bars: New.List(
           New.Obj(Prop:10000), 
           New.Obj(Prop:"Some Text") 
          ) 
         ) 
        ); 
} 

public interface IFoo 
{ 
    IList<dynamic> Bars { get; set; } 
} 
的[使用動態與.NET4泛型集合時無法理解的例外]
+0

謝謝噓 - 這指出我在正確的方向:) – user1297653 2013-04-15 06:55:32

+0

非常感謝!我即將失去它。 – rpattabi 2013-08-28 10:35:31

2

我不知道這是否顛覆你的特殊的使用情況,但:

嘗試明確鑄造BarsSystem.Collections.IList

((System.Collections.IList)foo.Bars).Add(a); 

來源:https://stackoverflow.com/a/9468123/364

或者,只是重新定義你的接口+類Bars作爲IList而非IList<dynamic>

相關問題