我有两个类,BaseClass
和Person
。 Person
类继承自 BaseClass
。然后我使用以下通用方法。
public static PropertyInfo GetProperty<T>(T item, Func<PropertyInfo, bool> predicate)
{
return GetProperty(typeof(T), predicate);
}
在BaseClass
中,我有一个方法,调用GetProperty
public class BaseClass
{
public void DoSomething()
{
var property = GetProperty(new Person(), (property) => p.Name == "Name");
}
}
我会在单元测试中调用这个方法。
var person = new Person();
person.DoSomething();
当使用
typeof(T)
时,返回BaseClass
。如果我使用item.GetType()
,则返回Person
。如果在调试器中检查它们,T
的类型是BaseClass
,而item
的类型是Person
。为什么它不推断出T
是typeof(Person)
,当它已经知道item
是一个人?
编辑
对不起,我的例子是错误的,当我调用GetProperty
时,我传递了this
。
public class BaseClass
{
public void DoSomething()
{
var property = GetProperty(this, (property) => p.Name == "Name");
}
}
T
=BaseClass
,那么程序仍将编译和运行,并且您将会看到您所描述的输出。一般情况下,应尽可能使用GetType()
,因为您将始终获得对象的具体类型。 - Steve GuidiBaseClass
的范围内,typeof(this)
总是会返回BaseClass
。然而,this.GetType()
被重载了并返回了Person
。 - Steve Guiditypeof(this)
会知道this
是一个子元素。谢谢。 - Johnathon SullingerDoSomething
中,您传递了this
,它是一个类型为BaseClass
的对象。因此编译器正确推断类型为BaseClass
。 - IS4