我尝试知道一个属性是否存在于类中,我尝试这样做:
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);
}
发布于 2013-03-11 22:33:15
您的方法如下所示:
public static bool HasProperty(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName) != null;
}
这为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");
发布于 2013-12-18 23:00:17
这回答了一个不同的问题:
如果试图找出一个对象(而不是类)是否具有属性,
OBJECT.GetType().GetProperty("PROPERTY") != null
如果(但不仅仅是如果)属性存在,则返回true。
在我的例子中,我在一个ASP.NET MVC局部视图中,并且希望在属性不存在或者属性(布尔值)为真的情况下呈现一些东西。
@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
Model.AddTimeoffBlackouts)
帮了我大忙。
编辑:现在,使用nameof
操作符而不是字符串化的属性名可能更明智。
发布于 2017-05-17 15:20:02
在绑定被接受的答案时,我得到了这样的错误:“类型不包含GetProperty的定义”。
这就是我最终得到的结论:
using System.Reflection;
if (productModel.GetType().GetTypeInfo().GetDeclaredProperty(propertyName) != null)
{
}
https://stackoverflow.com/questions/15341028
复制相似问题