静态方法中的GetType

Dan*_*ite 41 .net c# reflection

可能重复:
.NET:在其静态方法中确定"this"类的类型

如何GetType()static方法中访问?

我有这个抽象的基类

abstract class MyBase
{
   public static void MyMethod()
   {
      var myActualType = GetType(); // this is an instance method
      doSomethingWith(myActualType);
   }
}
Run Code Online (Sandbox Code Playgroud)

以及该类的实现.(我可以有很多实现.)

class MyImplementation : MyBase 
{
    // stuff
}
Run Code Online (Sandbox Code Playgroud)

我怎么能myActualType成为typeof(MyImplementation)

Ree*_*sey 47

静态方法中的"类型"始终是特定类型,因为不存在虚拟静态方法.

在你的情况下,这意味着你可以写:

 var myActualType = typeof(MyBase);
Run Code Online (Sandbox Code Playgroud)

由于MyMethod静态的"类型" 始终是静态方法MyBase.

  • @ mjd79:是的 - 但这是我的观点 - 静态方法总是会在基类型中输入,因为静态方法是类型的一部分,而不是使用方法的类... (3认同)

mat*_*att 23

那这个呢?

abstract class MyBase<T>
{
   public static void MyMethod()
   {
      var myActualType = typeof(T);
      doSomethingWith(myActualType);
   }
}


class MyImplementation : MyBase<MyImplementation>
{
    // stuff
}
Run Code Online (Sandbox Code Playgroud)

  • 什么阻止你做`类Bar:MyBase <Foo>`? (5认同)
  • 我们可以根据https://msdn.microsoft.com/en-us/library/d5x73970.aspx做`哪里T:<基类名称>` (3认同)

Dan*_*ite 3

这是我使用的模式。

abstract class MyBase
{
   public static void MyMethod(Type type)
   {
      doSomethingWith(type);
   }
}
Run Code Online (Sandbox Code Playgroud)