سؤال

this might be an easy one but I am really not getting it.

As far as I understand: The most dynamic types ins C# rely on IDictionary<string,object>

I did a spike with WebMatrix.Data and I would like to cast my result to IDictionary<string,object> but this does not work... WebMatrix.Data query returns an IEnumerable<DynamicRecord> This is what I try to cast...

here is my naiv code ...

var o = (DynamicObject) webmatrixRecord; // No Exception but o is still DynamicRecord

var o = (IDictionary<string,object>) webmatrixRecord; // Runtime Binder Exception

var o = ((IDictionary<string,object>)((DynamicRecord)webmatrixRecord)) // InvalidCastException;

So what is a proper way to cast an Dynamic object?

WebMatrix.DynamicRecord: http://msdn.microsoft.com/de-de/library/webmatrix.data.dynamicrecord(v=vs.111).aspx

Dynamics.DynamicRecord: http://msdn.microsoft.com/de-de/library/system.dynamic.dynamicobject(v=vs.111).aspx

هل كانت مفيدة؟

المحلول

The most dynamic types ins C# rely on IDictionary<string,object>

Not necessarily. ExpandoObject does, but there are plenty of other ways of being dynamic, and DynamicObject doesn't.

Note that reference conversion casting doesn't change the type of an object. So where you've got this line:

var o = (DynamicObject) webmatrixRecord; 

... the type of the variable will be DynamicObject, but that doesn't change the type of the object that the value of o refers to.

For your other casts, it seems that it just doesn't implement IDictionary<string, object>, so you can't cast to it. You could use DynamicObject.GetDynamicMemberNames to get the dynamic names, and then use DynamicObject.TryGetMember to get the values. It's not ideal though - I would personally try to avoid even having the requirement, if possible...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top