我试图知道类中是否存在属性,我try 了以下方法:

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

您的方法要求类的值为instance,而不是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) 为扩展提供instance个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");

.net相关问答推荐

.NET Blazor-使用子组件中的处理程序方法进行双向数据绑定

Docker镜像mcr.microsoft.com/dotnet/aspnet:8.0不能在Windows上构建

在PowerShell中,XML子对象和属性是对象属性.它怎麽工作?

.NET最小API BadRequest响应不返回正文

从容器化客户端应用程序连接到 OPC-UA 服务器

避免函数和其他对象之间的相互递归的模式?

Visual Studio 2022 中的目标操作系统和目标运行时有什么区别?

与 Datagrid 的 SelectedItem 链接时的 WPF RadioButton 绑定问题

.NET Async / Await:状态机如何知道何时继续执行?

如何在 .Net Core EF 中组合多个条件表达式来过滤数据?

在 .NET 中获取执行 exe 路径的最佳方法是什么?

C#6.0 字符串插值本地化

如何让 DateTimePicker 显示一个空字符串?

如何将浮点数向上舍入到 C# 中最近的 int?

如果需要,将方案添加到 URL

测试没有预期的异常

Linq to SQL - 返回前 n 行

如何从头开始以编程方式配置 log4net(无配置)

可以从 C# 调用 C++ 代码吗?

如何为 Dapper 查询动态创建参数