简体   繁体   中英

C# Call an instance method of parent class from a static method in a secondary static class

I have a public class B that inherits from a class A. Class B has access to an instance method TMA(). The method TMA() is implemented in class A, and I do not have access to A. I have a secondary static class C that implements a static method GetValue(). I need to access the instance method TMA() via the static GetValue() method. One complication is that the method GetValue() gets called many times.

public class B : A
{
    ...
}

public static class C
{
    public static double GetValue()
    {
        double result = 0;
        result = TMA(); // <--- I would like to do this but it does not work.
        return result;
    }
}

I have tried the following, and although it compiles, it crashes the program on execution. It may be that the program is creating too many instances of the class B, but I am not sure.

public static class C
{
    public static double GetValue()
    {
        B b = new B();
        double result = 0;
        result = b.TMA(); // <--- This did not work.
        return result;
    }
}

I have also tried accessing the instance method TMA() via object reference, but that did not work.

public static class C
{
    public static double GetValue(..., B ob)
    {
        double result = 0;
        result = ob.TMA(); // <--- This did not work.
        return result;
    }
}

I have read about the singleton pattern but I do not see how that could help me. Any suggestions or advice would be greatly appreciated. Thank you.

Can you keep a static instance of B and just use it?

public static class C
{
    static B _theB = new B();

    public static double GetValue()
    {
        double result = 0;
        result = _theB.TMA(); 
        return result;
    }
}

Wht exaactly is TMA doing? Does it involve a particular A (or B) object?

Your third attempt would appear to be the most correct (depending on how you call) GetValue() . but it would be helpful to know exactly how it "did not work.". (Did it crash? fail to compile? What was the error message?)

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