C# 成员函数中如何拿到当前所在类的名字?
C# 成员函数中如何拿到当前所在类的名字?
在 C# 中,在类的成员函数(实例方法)中获取当前类的名称,有几种常用方法:
1. 使用 this.GetType()
(推荐)
public class MyClass
{public void PrintClassName(){string className = this.GetType().Name; // 类名(不含命名空间)string fullName = this.GetType().FullName; // 完全限定名(含命名空间)Console.WriteLine(className); // 输出 "MyClass"Console.WriteLine(fullName); // 输出 "Namespace.MyClass"(如果有命名空间)}
}
- 适用场景:适用于实例方法,能正确反映运行时类型(包括继承的情况)。
- 注意:如果子类继承
MyClass
,this.GetType().Name
会返回子类的名称。
2. 使用 nameof
(编译时确定)
public class MyClass
{public void PrintClassName(){string className = nameof(MyClass); // 编译时替换为 "MyClass"Console.WriteLine(className); // 输出 "MyClass"}
}
- 适用场景:适用于编译时已知类名,不受继承影响(即使子类调用,仍然返回
MyClass
)。 - 优点:性能最佳(编译时静态解析)。
3. 使用 typeof(MyClass)
public class MyClass
{public void PrintClassName(){string className = typeof(MyClass).Name; // 类名(不含命名空间)string fullName = typeof(MyClass).FullName; // 完全限定名(含命名空间)Console.WriteLine(className); // 输出 "MyClass"Console.WriteLine(fullName); // 输出 "Namespace.MyClass"}
}
- 适用场景:适用于编译时已知类名,不受实例影响(静态方法也可用)。
- 注意:和
nameof
类似,不受继承影响。
4. 使用 MethodBase.GetCurrentMethod()
(反射方式,适用于静态方法)
using System.Reflection;public class MyClass
{public void PrintClassName(){string className = MethodBase.GetCurrentMethod().DeclaringType.Name;Console.WriteLine(className); // 输出 "MyClass"}
}
- 适用场景:适用于静态方法或无法使用
this
的情况。 - 缺点:性能较差(反射开销)。
如何选择?
方法 | 适用场景 | 是否受继承影响 | 性能 |
---|---|---|---|
this.GetType().Name | 实例方法,需运行时类型 | ✔️ 是(返回实际类型) | 一般 |
nameof(MyClass) | 编译时已知类名 | ❌ 否(固定类名) | 最佳 |
typeof(MyClass).Name | 编译时已知类名 | ❌ 否(固定类名) | 最佳 |
MethodBase (反射) | 静态方法或无 this 时 | ✔️ 是 | 较差 |
示例:继承情况下的区别
public class ParentClass
{public void PrintName(){Console.WriteLine(this.GetType().Name); // 实际类型(可能是子类)Console.WriteLine(nameof(ParentClass)); // 固定 "ParentClass"Console.WriteLine(typeof(ParentClass).Name); // 固定 "ParentClass"}
}public class ChildClass : ParentClass { }// 测试
var child = new ChildClass();
child.PrintName();
输出:
ChildClass // this.GetType().Name
ParentClass // nameof
ParentClass // typeof
总结
- 如果想获取 运行时实际类型(包括继承情况),用
this.GetType().Name
。 - 如果只需要 当前类的编译时名称(不受继承影响),用
nameof(MyClass)
或typeof(MyClass).Name
。 - 如果是在 静态方法 里,可以用
MethodBase.GetCurrentMethod().DeclaringType.Name
或typeof(MyClass).Name
。