如果我有一个继承自 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/