在C#中,使用反射查找一个类是否有属性的最佳方法是什么?

9
我有一个类
 public class Car
 {
       public string Name {get;set;}
       public int Year {get;set;}
 }

在另一段代码中,我有一个字段名为字符串(我们以“Year”为例)。
我想要做这样的事情:
   if (Car.HasProperty("Year")) 

它将确定汽车对象中是否存在“Year”字段。这将返回true。

   if (Car.HasProperty("Model"))

would return false.

我看到了一些遍历属性的代码,但我想知道是否有更简洁的方法来确定单个字段是否存在。


4
"HasProperty" 会不会是一个更好的方法名? - David M
2个回答

20

这个扩展方法应该可以实现。

static public bool HasProperty(this Type type, string name)
{
    return type
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Any(p => p.Name == name);
}
如果你想检查非实例属性、私有属性或其他选项,可以在该语句中调整 BindingFlags 值。你的语法使用将不会完全与你提供的相同。相反:
if (typeof(Car).HasProperty("Year"))

9

由于您似乎只需要查找public属性,Type.GetProperty()可以胜任此工作:

if (typeof(Car).GetProperty("Year") != null) {
    // The 'Car' type exposes a public 'Year' property.
}

如果您想进一步抽象上述代码,可以在 Type class 上编写一个扩展方法:

public static bool HasPublicProperty(this Type type, string name)
{
    return type.GetProperty(name) != null;
}

然后像这样使用它:
if (typeof(Car).HasPublicProperty("Year")) {
    // The 'Car' type exposes a public 'Year' property.
}

如果您还希望检查非public属性的存在,您将需要调用带有BindingFlags参数的Type.GetProperties()的重载,并像David M在他的回答中所做的那样过滤结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接