相关疑难解决方法(0)

检查类中是否存在属性

我试着知道一个属性是否存在于类中,我试过这个:

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)

.net c# reflection

74
推荐指数
3
解决办法
10万
查看次数

标签 统计

.net ×1

c# ×1

reflection ×1