检查一个属性是否存在于类中

本文关键字:属性 是否 存在 于类中 一个 检查 | 更新日期: 2023-09-27 18:03:24

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

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

我不明白为什么第一个测试方法不通过?

[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);
}

检查一个属性是否存在于类中

你的方法是这样的:

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

这在everything的基类object上添加了一个扩展。当你调用这个扩展时,你传递给它一个Type:

var res = typeof(MyClass).HasProperty("Label");

你的方法需要一个类的实例,而不是一个Type。否则你实际上是在做

typeof(MyClass) - this gives an instanceof `System.Type`. 
然后

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

正如@PeterRitchie正确指出的那样,此时您的代码正在查找System.Type上的属性Label。该属性不存在。

解决方案是

a)提供MyClass的实例给扩展:
var myInstance = new MyClass()
myInstance.HasProperty("Label")

b)把扩展放在System.Type

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

typeof(MyClass).HasProperty("Label");

这回答了另一个问题:

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

OBJECT.GetType().GetProperty("PROPERTY") != null

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

在我的情况下,我在ASP。如果属性不存在,或者属性(布尔值)为真,想要渲染一些东西。

@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
        Model.AddTimeoffBlackouts)

帮了我的忙。

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

我得到这个错误:"Type不包含GetProperty的定义"当绑定接受的答案

这是我最后的结果:

using System.Reflection;
if (productModel.GetType().GetTypeInfo().GetDeclaredProperty(propertyName) != null)
{
}

有两种可能。

你真的没有Label属性。

你需要调用适当的GetProperty重载并传递正确的绑定标志,例如BindingFlags.Public | BindingFlags.Instance

如果你的属性不是公共的,你将需要使用BindingFlags.NonPublic或其他一些符合你用例的标志组合。参考API文档查找详细信息。

编辑:

哎呀,刚刚注意到你在typeof(MyClass)上调用了GetPropertytypeof(MyClass)Type,肯定没有Label属性。

如果你像我一样绑定:

<%# Container.DataItem.GetType().GetProperty("Property1") != null ? DataBinder.Eval(Container.DataItem, "Property1") : DataBinder.Eval(Container.DataItem, "Property2")  %>

我不确定为什么需要这个上下文,所以这可能不会为您返回足够的信息,但这是我能够做的:

if(typeof(ModelName).GetProperty("Name of Property") != null)
{
//whatevver you were wanting to do.
}

在我的情况下,我正在运行从表单提交的属性,也有默认值使用,如果条目是空的-所以我需要知道是否有一个值使用-我在模型中使用 default 前缀我所有的默认值,所以我需要做的就是检查是否有一个属性以它开始