c# - 获取声明类的名称?

标签 c# .net inheritance reflection

假设我有一个父类和一个子类:

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

这有可能吗?

注意:

I understand that I could use GetType().BaseType.Name but this won't work since the hierarchy could be complex.

最佳答案

我想你想要这个:

return MethodBase.GetCurrentMethod().DeclaringType.Name; 

关于c# - 获取声明类的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41247534/

相关文章:

c# - 使用 Expression 为对象赋值

.net - 哪些设计决策导致 StackOverflowException 在 .NET 2.0+ 中无法捕获?

.net - APN 失败并显示 "Authentication failed because the remote party has closed the transport stream"

class - 从抽象类继承的案例类

python - 继承 View 的问题 - Odoo 模块

java - Java 继承是否会创建一个隐藏的父对象?

c# - 何时以及为何使用 C# 访问器方法

c# - 在 Startup.cs 中生成角色在 .NET Core 2.0 中不再起作用

c# - EF4 代码优先 : how to update specific fields only

java - 混淆 java 与 .net 应用程序,两者几乎相同吗?