简体   繁体   English

C#反射和静态成员的继承

[英]C# reflection and inheritance of static members

Let's say we have these two classes: 假设我们有以下两个类:

public class Base
{
    public static int GetInt() { return 1; }
}

public class Derived : Base
{

}

Let's also say that a piece of code calls Derived.GetInt(). 我们还假设一段代码调用Derived.GetInt()。 How can I tell from within GetInt() that it was Derived.GetInt() and not Base.GetInt() that was called? 我如何从GetInt()内部得知它是Derived.GetInt()而不是被调用的Base.GetInt()? What reflection technique do I use? 我使用什么反射技术?

There's no way to tell the difference, with Reflection or otherwise. 无论是使用反射还是其他方法,都无法分辨出差异。 The calls are precisely equivalent, and when compiling, already at MSIL level there is no difference. 这些调用完全等效,并且在编译时已经处于MSIL级别,没有区别。

I don't think you do, since there is no Derived.GetInt. 我不认为你这样做,因为没有 Derived.GetInt。 GetInt is a static member, and although you're referencing it through Derived, it only belongs to Base. GetInt是静态成员,尽管您通过Derived引用它,但它仅属于Base。

Since the method GetInt is a static method, and not an instance method, it will always be called from the base class. 由于方法GetInt是静态方法,而不是实例方法,因此将始终从基类中调用它。 You can't truly call it from the derived class, because you aren't calling it from an instance. 您不能真正从派生类中调用它,因为您不是从实例中调用它。

You can do this if you want to have different functionality based on the class that the method is called through. 如果您希望基于调用该方法的类具有不同的功能,则可以执行此操作。

void Main()
{
   Console.WriteLine( Base.GetInt() ); // 1
   Console.WriteLine( Derived.GetInt() );  // 2
}

public class Base
{
 public static int GetInt() 
 { 
   return 1; 
 }
}

public class Derived : Base
{
  public static int GetInt()
  {
    return 2;
  }
}

It's probably best to think of static methods simply as global functions. 最好将静态方法简单地视为全局函数。 The class name serves as an extended namespace. 类名用作扩展名称空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM