문제

I am trying to understand c# dynamic. I have an ExpandoObject instance assigned to dynamic variable. I understand ExpandoObject is implementing IDictionary. But the below assignment fails.

dynamic obj = new ExpandoObject();
obj["Test"] = "TestValue";
Console.WriteLine(obj.Test);

Can someone tell me where i am going wrong?

obj.Test="TestValue";

However the above statement seems to be working fine.

도움이 되었습니까?

해결책

To do that, you need to cast the ExpandoObject to IDictionary<string, object>.

This is normal Expando usage:

obj.Test = "TestValue";

This is string-literal (or string variable) usage:

var d = (IDictionary<string, object>)obj;
d["Test"] = "TestValue";

string s = "Test";
d[s] = "TestValue";

If the interface implementation is explicit, you need to cast to a reference of the interface in order to access the members. I'm guessing this is what has happened here.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top