gpt4 book ai didi

c# - 在运行时以静态方法获取当前类?

转载 作者:行者123 更新时间:2023-11-30 14:59:52 24 4
gpt4 key购买 nike

如何在抽象类的静态方法中获取当前类的类型(不是名称字符串,而是类型本身)?

using System.Reflection; // I'll need it, right?

public abstract class AbstractClass {

private static void Method() {

// I want to get CurrentClass type here

}

}

public class CurrentClass : AbstractClass {

public void DoStuff() {

Method(); // Here I'm calling it

}

}

这个问题与这个问题非常相似:

How to get the current class name at runtime?

但是,我想从静态方法内部获取这些信息。

最佳答案

public abstract class AbstractClass
{
protected static void Method<T>() where T : AbstractClass
{
Type t = typeof (T);

}
}

public class CurrentClass : AbstractClass
{

public void DoStuff()
{
Method<CurrentClass>(); // Here I'm calling it
}

}

只需将类型作为泛型类型参数传递给基类,即可从静态方法访问派生类型。

关于c# - 在运行时以静态方法获取当前类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16120753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com