Get Static Member of Parent Class from Child Inherited Class

Let's say I have,

public class A
{
    public static void MyAMethod()
    {
    }

    public class B
    {

    }        
}

public class C : A.B
{
    public void MyCMethod()
    {
        MyAMethod();// I need to call this
    }
}

Now I need to call MyAMethod from class C.

Edit: In my situation class A is unavailable. So, I cannot use A.MyAMethod.

Answers


If you take a look at the IL code for

namespace NestedTest
{
    public class A
    {
        public static void MyAMethod()
        {
            System.Console.WriteLine("public static void MyAMethod()");
        }

        public class B
        {
            public void MyBMethod()
            {
                MyAMethod();
            }
        }
    }
}

you will find that MyBMethod is implemented(?) as

.method public hidebysig instance void  MyBMethod() cil managed
{
  // Code size       8 (0x8)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  call       void NestedTest.A::MyAMethod()
  IL_0006:  nop
  IL_0007:  ret
} // end of method B::MyBMethod

As you can see the call to NestedTest.A::MyAMethod() is hard-coded i.e. the "magic" was already done by the C#->IL compiler. (*) You could get the information you need to call the static method via reflection, e.g. (without error handling and rather crude)

public class C : A.B
{
    public void MyCMethod()
    {
        Type parent = GetType().BaseType;
        Type outer = parent.DeclaringType;
        System.Reflection.MethodInfo mi = outer.GetMethod("MyAMethod");
        mi.Invoke(null, null);
        return;
    }
}

but there is probably a better solution for your specific problem.


(*) and the c# compiler does that only as specified in http://msdn.microsoft.com/en-us/library/ms228593.aspx

3.7 Scopes

The scope of a name is the region of program text within which it is possible to refer to the entity declared by the name without qualification of the name [...]

- The scope of a member declared by a class-member-declaration (§10.1.6) is the class-body in which the declaration occurs. In addition, the scope of a class member extends to the class-body of those derived classes that are included in the accessibility domain (§3.5.2) of the member.

class B is part of the class-body of class A, class C is not. And class C is also not derived from class A.


You can just call A.MyAMethod() from inside your method since it is static


Need Your Help

Matching the Same Number of Chars that was Captured by a Previous Group

regex expression

Using regular expressions, is it possible to match a number of characters corresponding to the length of a previously captured group ?

Worklight: multiple security realms

security authentication worklight

I want to know can we have multiple same name security tests defined in the authenticationconfig.xml file?