[英]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(). 我有一个从类A继承的公共类B。类B可以访问实例方法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().
方法TMA()在类A中实现,我无权访问A。我有一个辅助静态类C,它实现了静态方法GetValue()。 I need to access the instance method TMA() via the static GetValue() method.
我需要通过静态GetValue()方法访问实例方法TMA()。 One complication is that the method GetValue() gets called many times.
一种复杂的情况是方法GetValue()被多次调用。
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.
可能是程序创建了太多的B类实例,但是我不确定。
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. 我也尝试通过对象引用访问实例方法TMA(),但这没有用。
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? 您可以保留
B
的静态实例并使用它吗?
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? TMA到底在做什么? Does it involve a particular A (or B) object?
它是否涉及特定的A(或B)对象?
Your third attempt would appear to be the most correct (depending on how you call) GetValue()
. 您的第三次尝试似乎是最正确的(取决于您的调用方式)
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?)
(它崩溃了吗?编译失败?错误消息是什么?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.