我试试就知道如果一个属性存在的一类,我想这样的:
公共静态布尔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");
相关推荐
最新文章