![](/img/trans.png)
[英]C#: How do I call a static method of a base class from a static method of a derived class?
[英]C# Call an instance method of parent class from a static method in a secondary static class
我有一個從類A繼承的公共類B。類B可以訪問實例方法TMA()。 方法TMA()在類A中實現,我無權訪問A。我有一個輔助靜態類C,它實現了靜態方法GetValue()。 我需要通過靜態GetValue()方法訪問實例方法TMA()。 一種復雜的情況是方法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;
}
}
我嘗試了以下方法,盡管可以編譯,但在執行時會使程序崩潰。 可能是程序創建了太多的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;
}
}
我也嘗試通過對象引用訪問實例方法TMA(),但這沒有用。
public static class C
{
public static double GetValue(..., B ob)
{
double result = 0;
result = ob.TMA(); // <--- This did not work.
return result;
}
}
我已經閱讀了有關單例模式的信息,但我看不出這對我有什么幫助。 任何建議或意見,將不勝感激。 謝謝。
您可以保留B
的靜態實例並使用它嗎?
public static class C
{
static B _theB = new B();
public static double GetValue()
{
double result = 0;
result = _theB.TMA();
return result;
}
}
TMA到底在做什么? 它是否涉及特定的A(或B)對象?
您的第三次嘗試似乎是最正確的(取決於您的調用方式) GetValue()
。 但是准確了解它“沒有起作用”是有幫助的。 (它崩潰了嗎?編譯失敗?錯誤消息是什么?)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.