【问题标题】:Getting the name of the declaring class?获取声明类的名称?
【发布时间】: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() 应该返回 ChildGetParentName() 应该返回 Parent

这有可能吗?

注意:

我知道我可以使用 GetType().BaseType.Name 但这 行不通,因为层次结构可能很复杂。

【问题讨论】:

  • I'd like to get the name of the class in which the method is declared 我的意思是它们是两种不同的方法,GetChildName is 在子级中声明
  • 您可以简单地返回“父母”。给我们一个不适合返回字符串字面量的例子。

标签: c# .net inheritance reflection


【解决方案1】:

你想要这个,我想:

return MethodBase.GetCurrentMethod().DeclaringType.Name; 

【讨论】:

  • 如果您希望能够从相关函数之外的某个位置获取声明类型,您也可以使用它:typeof(Child).GetMembers().First(m => m. Name == "GetParentName").DeclaringType.Name
猜你喜欢
  • 1970-01-01
  • 2011-11-21
  • 2016-07-18
  • 2017-06-19
  • 2011-05-31
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
相关资源
最近更新 更多