C# 检查类中是否存在属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15341028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:28:33  来源:igfitidea点击:

Check if a property exists in a class

c#.netreflection

提问by Kris-I

I try to know if a property exist in a class, I tried this :

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

public static bool HasProperty(this object obj, string propertyName)
{
    return obj.GetType().GetProperty(propertyName) != null;
}

I don't understand why the first test method does not pass ?

我不明白为什么第一个测试方法没有通过?

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

采纳答案by Jamiec

Your method looks like this:

您的方法如下所示:

public static bool HasProperty(this object obj, string propertyName)
{
    return obj.GetType().GetProperty(propertyName) != null;
}

This adds an extension onto object- the base class of everything. When you call this extension you're passing it a Type:

这将扩展添加到所有内容object的基类。当您调用此扩展程序时,您将传递给它:Type

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

Your method expects an instanceof a class, not a Type. Otherwise you're essentially doing

您的方法需要一个类的实例,而不是一个Type. 否则你基本上是在做

typeof(MyClass) - this gives an instanceof `System.Type`. 

Then

然后

type.GetType() - this gives `System.Type`
Getproperty('xxx') - whatever you provide as xxx is unlikely to be on `System.Type`

As @PeterRitchie correctly points out, at this point your code is looking for property Labelon System.Type. That property does not exist.

作为@PeterRitchie正确地指出,在这一点上你的代码是找物业LabelSystem.Type。该属性不存在。

The solution is either

解决方案是

a) Provide an instanceof MyClass to the extension:

a) 为扩展提供一个MyClass实例

var myInstance = new MyClass()
myInstance.HasProperty("Label")

b) Put the extension on System.Type

b) 安装扩展 System.Type

public static bool HasProperty(this Type obj, string propertyName)
{
    return obj.GetProperty(propertyName) != null;
}

and

typeof(MyClass).HasProperty("Label");

回答by Zdeslav Vojkovic

There are 2 possibilities.

有2种可能性。

You really don't have Labelproperty.

你真的没有Label财产。

You need to call appropriate GetProperty overloadand pass the correct binding flags, e.g. BindingFlags.Public | BindingFlags.Instance

您需要调用适当的GetProperty 重载并传递正确的绑定标志,例如BindingFlags.Public | BindingFlags.Instance

If your property is not public, you will need to use BindingFlags.NonPublicor some other combination of flags which fits your use case. Read the referenced API docs to find the details.

如果您的财产不是公开的,您将需要使用BindingFlags.NonPublic适合您的用例的标志或其他一些标志组合。阅读引用的 API 文档以查找详细信息。

EDIT:

编辑:

ooops, just noticed you call GetPropertyon typeof(MyClass). typeof(MyClass)is Typewhich for sure has no Labelproperty.

哎呀,刚刚注意到你打电话GetPropertytypeof(MyClass)typeof(MyClass)Type肯定没有Label财产。

回答by Stachu

This answers a different question:

这回答了一个不同的问题:

If trying to figure out if an OBJECT (not class) has a property,

如果试图弄清楚 OBJECT(不是类)是否具有属性,

OBJECT.GetType().GetProperty("PROPERTY") != null

returns true if (but not only if) the property exists.

如果(但不仅限于)该属性存在,则返回 true。

In my case, I was in an ASP.NET MVC Partial View and wanted to render something if either the property did not exist, or the property (boolean) was true.

就我而言,我在 ASP.NET MVC Partial View 中,并且想要在属性不存在或属性(布尔值)为真时呈现某些内容。

@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
        Model.AddTimeoffBlackouts)

helped me here.

在这里帮助了我。

Edit: Nowadays, it's probably smart to use the nameofoperator instead of the stringified property name.

编辑:如今,使用nameof运算符而不是字符串化的属性名称可能是明智之举。

回答by Ben

If you are binding like I was:

如果你像我一样绑定:

<%# Container.DataItem.GetType().GetProperty("Property1") != null ? DataBinder.Eval(Container.DataItem, "Property1") : DataBinder.Eval(Container.DataItem, "Property2")  %>

回答by Tadej

I got this error: "Type does not contain a definition for GetProperty" when tying the accepted answer.

绑定接受的答案时,我收到此错误:“类型不包含 GetProperty 的定义”。

This is what i ended up with:

这就是我最终的结果:

using System.Reflection;

if (productModel.GetType().GetTypeInfo().GetDeclaredProperty(propertyName) != null)
{

}

回答by C Gil

I'm unsure of the context on why this was needed, so this may not return enough information for you but this is what I was able to do:

我不确定为什么需要这样做的上下文,因此这可能无法为您返回足够的信息,但这是我能够做的:

if(typeof(ModelName).GetProperty("Name of Property") != null)
{
//whatevver you were wanting to do.
}

In my case I'm running through properties from a form submission and also have default values to use if the entry is left blank - so I needed to know if the there was a value to use - I prefixed all my default values in the model with Defaultso all I needed to do is check if there was a property that started with that.

在我的情况下,我正在运行表单提交中的属性,并且如果条目留空,也有默认值要使用 - 所以我需要知道是否有一个值可以使用 - 我在模型中添加了所有默认值的前缀使用默认值,所以我需要做的就是检查是否有一个以它开头的属性。