Is Reflection the best way to determine the presense/absence of property/method on a dynamic object?
I have a number of data access methods that accept a dynamic object parameter (i.e., dynamic foo). I can't use an interface to define to type the input parameter due to existing code. I am setting properties in the data access methods, but using dynamic without checking to see if the properties/methods exist makes me nervous.
So I am looking for a way to check the runtime properties/methods of a dynamic object, but I would rather not use reflection due to the performance impact. Is there another/recommended way to query the properties/methods of a dynamic object?
Tha开发者_运维技巧nks, Erick
Reflection doesn't actually work (the way you'd expect) on dynamic
types. You need to check for IDynamicMetaObjectProvider
, then use its methods to determine whether a member is available on the type.
The problem is that it's perfectly acceptable for a dynamic
type to add new members at runtime. For an example, see ExpandoObject. It only adds new members on set operations, but you can, just as easily, make a dynamic type that always returns a valid member, no matter what is passed into it, ie:
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, reflection would have no way to tell what would work here...
I would look at this problem a bit differently. If you're using the objects with dynamic
then whether or not the properties are accessible via reflection is irrelevant. It only matters if they are accessible via dynamic
. So why not just use the properties and catch the execption that would result from their abscence?
精彩评论