簡短的回答:
試試這個:
public static void loadAnotherRemote()
{
new TypeThatContainsCloseComm(…).closeComm();
}
較長的答案:
首先,你需要了解static
:不管被宣佈爲static
不屬於到任何特定的實例的類型,但屬於類型本身。也就是說,如果你有一個靜態方法TypeThatContainsCloseComm.closeComm
,那麼你就可以把它叫做:
TypeThatContainsCloseComm.closeComm(…)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
// name of the type!
但是,未申報static
只能在特定實例被調用,因爲這是所有方法,他們屬於什麼於:
var commProj = new TypeThatContainsClosePort(); // <- create a instance here
commProj.ClosePort();
// ^^^^^^^^
// instance of a type!
現在,回到你原來的代碼:
public void closeComm()
{
commIRToy.ClosePort();
commProj.ClosePort();
commTV.ClosePort();
commAV.ClosePort();
}
public static void loadAnotherRemote()
{
// this method is static, therefore we are not "within" an object instance
closeComm(); // ERROR: closeComm is not static, therefore you need
// some object instance to call it!
}
&hellip;並返回到第二次嘗試:
public static void closeComm()
{
commIRToy.ClosePort(); // ERROR if commIRToy, commProj, commTV, commAV
commProj.ClosePort(); // are not declared static, because we're
commTV.ClosePort(); // in a static method and thus "outside" an
commAV.ClosePort(); // object instance, yet these fields are
} // declared within one.
public static void loadAnotherRemote()
{
closeComm(); // this call is fine now, since `closeComm` is static,
// no object instance is required to call it.
}
您的loadAnotherRemote()方法是靜態的嗎? – BoltClock
歡迎來到[SO]。很高興有你的問題,但請注意:1)沒有「C Sharp」這樣的東西。該語言是「C#」。 2)你不需要在標題中加入「C Sharp」這樣的東西 - 我們有標籤。 –
關於術語的離題建議:在C#中,類型的可執行位稱爲**「methods」**,而不是「functions」。這兩個術語之間的一般概念是前者(方法)是一個類型的成員,而後者(函數)可以由他們自己存在,即。在一個類型之外。可能的例外情況:(1)「代表」。但是,即使這些不被稱爲「函數指針」,因爲它們是不同的東西。 (2)lambda表達式('(...)=> {...}')和匿名委託('delegate(...){...}');但即使這些通常被稱爲匿名方法,從來沒有「功能」。 – stakx