c# - 获取当前类名包括父类名?

标签 c# .net

如果我有一个继承自 A 的类 B 和 C,是否有比使用 StackFrame 的 GetFileName()(然后解析出 ClassName.cs 字符串)更简单的方法?

如果我使用 this.GetType().Name,当代码在父类中执行时,它不会返回“A”。

示例代码

namespace StackOverflow.Demos
{
    class Program
    {
        public static void Main(string[] args)
        {
            B myClass = new C();
            string containingClassName = myClass.GetContainingClassName();
            Console.WriteLine(containingClassName); //should output StackOverflow.Demos.B
            Console.ReadKey();
        }
    }

    public class A { public A() { } }
    public class B : A { public B() { } }
    public class C : B { public C() { } }

}

最佳答案

var yourType = GetType();
var baseType = yourType.BaseType;

或者:

var currentTypeName = new StackFrame(1, false).GetMethod().DeclaringType.Name;

关于c# - 获取当前类名包括父类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13314290/

相关文章:

c# - 如何在 Silverlight 中使用 OpenXml (Office)?

c# - XML 将所有子元素重命名为相同的标签名称

c# - 将对象转换为集合

c# - List<string> 到 List<DateTime>

.net - WPF中的默认光标?

c# - LINQ on 循环条件

c# - 检查 PropertyDescriptor 是否有属性

C# - DataGridView 和 SelectedCells - 查找选定单元格的行索引

c# - 通过互操作将 VB6 对象传递给 .NET 对象?

c++ - 如何计算 C++ Visual Studio 中两个日期之间的天数?