c#从列表<t>初始化expandoobject

时间:2017-04-14 12:50:38

标签: c# dynamic expandoobject

我想从List初始化一个expandoObject。

internal class CarKeyValue {
    public CarKey CarKey { get; set; }
    public string Value1 { get; set; }
    public string Value2 { get; set; }
}

public enum CarKey {
    Brand = 1,
    Model = 2,
    Year = 3,
    FactoryLocation = 4,
    //more than 400 key here...
}

var car = new List<CarKeyValue>{
    new CarKeyValue {CarKey = CarKey.Brand, Value1 = "Ford"},
    new CarKeyValue {CarKey = CarKey.Model, Value1 = "Focus",Value2 = "Titanium"},
    new CarKeyValue {CarKey = CarKey.Year, Value1 = "1995"},
    new CarKeyValue {CarKey = CarKey.FactoryLocation, Value1 = "Turkey",Value2="Bursa"},
        };

dynamic expando = new ExpandoObject();
foreach(var item in car){
    expando.[item.CarKey].Value1 = item.Value1;
//Incorrect primary expression.
    expando.[item.CarKey].Value2 = item.Value2;
}

我是怎么做到的?我需要使用Expando Object。我尝试使用IDictionary<string,dynamic>但是引发了另一个异常。

有可能吗?

2 个答案:

答案 0 :(得分:0)

是的,你可以,但没有任何意义。您必须将expando对象强制转换为IDictionary<string, object>IDictionary<string, dynamic>

IDictionary<string, object> expando = new ExpandoObject();
foreach (var item in car)
{
    expando[item.CarKey.ToString()].Value1 = item.Value1;
}

上述代码失败,因为您从未为expando[item.CarKey.ToString()]分配值。相反,您想要从不存在的对象设置属性。常规代码会抛出NullReferenceException。 (您可以将上述代码读作expando.SomeProperty.Value1,其中SomePropertynull。)

因此,一旦将对象设置为某个实例,就可以使用它,但是再使用ExpandoObject没有多大用处:

Foo foo = new Foo();
expando[item.CarKey.ToString()] = foo;
foo.Value1 = item.Value1;

答案 1 :(得分:0)

我的解决方案就在这里。我使用IDictionary。不需要使用Foo()或其他东西。此代码块运行良好。

IDictionary<string,dynamic> expando = new ExpandoObject();
foreach(var item in car) {
     expando.Add(item.CarKey.ToString(),null);
     expando[item.CarKey.ToString()] = new { Value1 = item.Value1,Value2 = item.Value2 };
}