【发布时间】:2017-05-05 23:27:11
【问题描述】:
假设我有一个父类和一个子类:
public abstract class Parent
{
public string GetParentName()
{
return GetType().Name;
}
}
public class Child : Parent
{
public string GetChildName()
{
return GetType().Name;
}
}
目前,GetParentName() 和 GetChildName() 都将返回 Child。
但是,在我的场景中,我想获取声明该方法的类的名称。
因此 GetChildName() 应该返回 Child 但 GetParentName() 应该返回 Parent。
这有可能吗?
注意:
我知道我可以使用 GetType().BaseType.Name 但这 行不通,因为层次结构可能很复杂。
【问题讨论】:
-
I'd like to get the name of the class in which the method is declared我的意思是它们是两种不同的方法,GetChildNameis 在子级中声明 -
您可以简单地返回“父母”。给我们一个不适合返回字符串字面量的例子。
标签: c# .net inheritance reflection