c# - 检查类中是否存在属性

标签 c# .net reflection

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

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

这会在 object 上添加一个扩展 - everything 的基类。当您调用此扩展程序时,您将向其传递一个 Type:

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

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

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");

关于c# - 检查类中是否存在属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15341028/

相关文章:

c# - 我可以从 NHibernate 获取底层连接和事务对象吗?

c# - 在同步框架中配置适配器

c# - 来自 SQLCLR 的异步 API 调用中的问题

java - 使用 class.forname().newInstance() 实例化类时出错

c# - 在 C# 中将类成员引用为枚举

c# - 在 C# 中 gRPC\Protobuf 中的反射

c# - 创建 Xamarin 插件/用户控件库

c# - 使用类来保存与软件消息相关的字符串

.net - ContextType.ApplicationDirectory 上的 AD LDS ValidateCredentials 无法进行身份验证

c# - 自定义用户控件中的 ASP 嵌套标记