测试属性是否可以在一个动态的变量 [英] Test if a property is available on a dynamic variable

查看:273
本文介绍了测试属性是否可以在一个动态的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况很简单。某处在我的code我有这样的:

My situation is very simple. Somewhere in my code I have this:

dynamic myVariable = GetDataThatLooksVerySimilarButNotTheSame();

//How to do this?
if (myVariable.MyProperty.Exists)   
//Do stuff

所以,基本上我的问题是如何检查(未抛出异常),某财产可在我的动态变量。我可以做的GetType()但我宁愿避免这种情况,因为我并不需要知道对象的类型。这一切我真的想知道的是属性是否(或方法,如果让生活更轻松)可用。任何指针?

So, basically my question is how to check (without throwing an exception) that a certain property is available on my dynamic variable. I could do GetType() but I'd rather avoid that since I don't really need to know the type of the object. All that I really want to know is whether a property (or method, if that makes life easier) is available. Any pointers?

推荐答案

我觉得没有办法找出一个动态变量是否具有一定的成员,但不尝试访问它,除非你重新实现动态绑定在C#编译器处理方式。这可能会包括很多猜测,因为它是实现定义,根据C#规范。

I think there is no way to find out whether a dynamic variable has a certain member without trying to access it, unless you re-implemented the way dynamic binding is handled in the C# compiler. Which would probably include a lot of guessing, because it is implementation-defined, according to the C# specification.

所以,你应该真正尝试访问该成员和捕捉异常,如果失败:

So you should actually try to access the member and catch an exception, if it fails:

dynamic myVariable = GetDataThatLooksVerySimilarButNotTheSame();

try
{
    var x = myVariable.MyProperty;
    // do stuff with x
}
catch (RuntimeBinderException)
{
    //  MyProperty doesn't exist
} 

这篇关于测试属性是否可以在一个动态的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆