检查类中是否存在属性

Kri*_*s-I 74 .net c# reflection

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

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)

Jam*_*iec 105

您的方法如下所示:

public static bool HasProperty(this object obj, string propertyName)
{
    return obj.GetType().GetProperty(propertyName) != null;
}
Run Code Online (Sandbox Code Playgroud)

这将扩展到object- 所有内容的基类.当你拨打这个分机时,你传递的是Type:

var res = typeof(MyClass).HasProperty("Label");
Run Code Online (Sandbox Code Playgroud)

您的方法需要一个类的实例,而不是一个Type.否则你基本上就是在做

typeof(MyClass) - this gives an instanceof `System.Type`. 
Run Code Online (Sandbox Code Playgroud)

然后

type.GetType() - this gives `System.Type`
Getproperty('xxx') - whatever you provide as xxx is unlikely to be on `System.Type`
Run Code Online (Sandbox Code Playgroud)

作为@PeterRitchie正确地指出,在这一点上你的代码是找物业LabelSystem.Type.那个属性不存在.

解决方案是

a)向扩展提供MyClass 的实例:

var myInstance = new MyClass()
myInstance.HasProperty("Label")
Run Code Online (Sandbox Code Playgroud)

b)放置扩展名 System.Type

public static bool HasProperty(this Type obj, string propertyName)
{
    return obj.GetProperty(propertyName) != null;
}
Run Code Online (Sandbox Code Playgroud)

typeof(MyClass).HasProperty("Label");
Run Code Online (Sandbox Code Playgroud)

  • 即你的代码正在寻找`Type.Label`,而不是'MyClass.Label`. (2认同)

Sta*_*chu 20

这回答了一个不同的问题:

如果试图找出一个OBJECT(不是类)是否有属性,

OBJECT.GetType().GetProperty("PROPERTY") != null
Run Code Online (Sandbox Code Playgroud)

如果(但不仅仅是)属性存在,则返回true.

就我而言,我在ASP.NET MVC Partial View中,如果属性不存在或者属性(boolean)为true,则想要渲染一些内容.

@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
        Model.AddTimeoffBlackouts)
Run Code Online (Sandbox Code Playgroud)

在这帮助我

编辑:现在,使用nameof运算符而不是字符串化的属性名称可能很聪明.


Tad*_*dej 5

当绑定接受的答案时,我收到此错误:“类型不包含 GetProperty 的定义”。

这就是我最终得到的结果:

using System.Reflection;

if (productModel.GetType().GetTypeInfo().GetDeclaredProperty(propertyName) != null)
{

}
Run Code Online (Sandbox Code Playgroud)