检查如果一个属性存在于类 [英] Check if a property exist in a class

查看:195
本文介绍了检查如果一个属性存在于类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试试就知道如果一个属性存在的一类,我想这样的:

 公共静态布尔HasProperty(此obj对象,字符串propertyName的)
{
    返回obj.GetType()的getProperty(propertyName的)=空。!;
}
 

我不明白为什么第一次测试方法不及格?

  [TestMethod的]
公共无效Test_HasProperty_True()
{
    VAR解析度= typeof运算(MyClass的).HasProperty(标签);
    Assert.IsTrue(RES);
}

[测试方法]
公共无效Test_HasProperty_False()
{
    VAR解析度= typeof运算(MyClass的).HasProperty(实验室);
    Assert.IsFalse(RES);
}
 

解决方案

您的方法是这样的:

 公共静态布尔HasProperty(此obj对象,字符串propertyName的)
{
    返回obj.GetType()的getProperty(propertyName的)=空。!;
}
 

这增加了一个延伸到对象 - 中的一切的基类的。当你调用这个扩展你传递一个键入

  VAR RES = typeof运算(MyClass的).HasProperty(标签);
 

您的方法需要一个类的实例的,而不是一个键入。否则,你基本上做

 的typeof(MyClass的) - 这给了一个instanceof`System.Type`。
 

然后

  type.GetType() - 这给了`System.Type`
的getProperty('XXX') - 无论你提供尽可能xxx是不可能的`System.Type`
 

由于@PeterRitchie正确地指出,在这一点上你的code是找物业标签的System.Type 。该属性不存在。

解决方法是,

a)提供的的实例的MyClass的向延伸:

  VAR将myInstance =新MyClass的()
myInstance.HasProperty(标签)
 

b)将延长对的System.Type

 公共静态布尔HasProperty(这种类型的OBJ,串propertyName的)
{
    返回obj.GetProperty(propertyName的)!= NULL;
}
 

 的typeof(MyClass的).HasProperty(标签);
 

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

解决方案

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:

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

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

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 Label on System.Type. That property does not exist.

The solution is either

a) Provide an instance of MyClass to the extension:

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

b) Put the extension on System.Type

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

and

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

这篇关于检查如果一个属性存在于类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆