我的情况很简单.在我的代码的某处我有这个:
dynamic myVariable = GetDataThatLooksVerySimilarButNotTheSame();
//How to do this?
if (myVariable.MyProperty.Exists)
//Do stuff
Run Code Online (Sandbox Code Playgroud)
所以,基本上我的问题是如何检查(不抛出异常)我的动态变量上有某个属性可用.我可以做,GetType()但我宁愿避免,因为我真的不需要知道对象的类型.我真正想知道的是一个属性(或方法,如果让生活更轻松)是可用的.有什么指针吗?
我试着知道一个属性是否存在于类中,我试过这个:
public static bool HasProperty(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName) != null;
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么第一种测试方法没有通过?
[TestMethod]
public void Test_HasProperty_True()
{
var res = typeof(MyClass).HasProperty("Label");
Assert.IsTrue(res);
}
[TestMethod]
public void Test_HasProperty_False()
{
var res = typeof(MyClass).HasProperty("Lab");
Assert.IsFalse(res);
}
Run Code Online (Sandbox Code Playgroud)