Is reflection the best way to determine the presence / absence of a property / method on a dynamic object?

I have several data access methods that accept a parameter of a dynamic object (i.e. dynamic foo). I cannot use the interface to determine the type of input parameter due to existing code. I set properties in data access methods, but use dynamics without checking if properties / methods exist, which makes me nervous.

So, I'm looking for a way to test the properties / methods of a dynamic object, but I would prefer not to use reflection due to performance impact. Is there any other recommended way to query the properties / methods of a dynamic object?

Thanks Erick

+5
source share
2 answers

Reflection does not actually work (as you expected) on types dynamic. You need to check IDynamicMetaObjectProviderand then use its methods to determine if a member is available in the type.

The problem is that dynamicit is perfectly acceptable for a type to add new members at run time. For example, see ExpandoObject . It only adds new members to the given operations, but you can just as easily create a dynamic type that always returns a valid member, regardless of what is passed to it, that is:

dynamic myType = new DynamicFoo();
Console.WriteLine(myType.Foo);
Console.WriteLine(myType.Bar);
Console.WriteLine(myType.Baz);

This can be done by overriding the get accessor and just making them always valid. In this case, the reflection could not say that it will work here ...

+2
source

-. dynamic, , . , dynamic. , ?

+2

All Articles