简体   繁体   中英

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(). How can I tell from within GetInt() that it was Derived.GetInt() and not Base.GetInt() that was called? 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.

I don't think you do, since there is no Derived.GetInt. GetInt is a static member, and although you're referencing it through Derived, it only belongs to Base.

Since the method GetInt is a static method, and not an instance method, it will always be called from the base class. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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