Pergunta

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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top