[英]Check if a property exists in a class
我试图知道一个类中是否存在一个属性,我试过这个:
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
的扩展 -一切的基类。 当你调用这个扩展时,你传递了一个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(不是类)是否有一个属性,
OBJECT.GetType().GetProperty("PROPERTY") != null
如果(但不仅限于)该属性存在,则返回 true。
就我而言,我在 ASP.NET MVC Partial View 中,并且想要在属性不存在或属性(布尔值)为真时呈现某些内容。
@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
Model.AddTimeoffBlackouts)
在这里帮助了我。
编辑:如今,使用nameof
运算符而不是字符串化的属性名称可能是明智之举。
有2种可能性。
你真的没有Label
属性。
您需要调用适当的GetProperty 重载并传递正确的绑定标志,例如BindingFlags.Public | BindingFlags.Instance
BindingFlags.Public | BindingFlags.Instance
如果您的财产不是公开的,您将需要使用BindingFlags.NonPublic
或适合您的用例的其他标志组合。 阅读引用的 API 文档以查找详细信息。
编辑:
哎呀,刚刚注意到您在typeof(MyClass)
上调用了GetProperty
。 typeof(MyClass)
是Type
,它肯定没有Label
属性。
绑定接受的答案时,我收到此错误:“类型不包含 GetProperty 的定义”。
这就是我最终的结果:
using System.Reflection;
if (productModel.GetType().GetTypeInfo().GetDeclaredProperty(propertyName) != null)
{
}
如果你像我一样绑定:
<%# 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.
}
在我的情况下,我正在运行表单提交中的属性,并且如果条目留空,也有默认值要使用 - 所以我需要知道是否有一个值可以使用 - 我在模型中添加了所有默认值的前缀使用默认值,所以我需要做的就是检查是否有一个以它开头的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.