Краткий ответ:
Попробуйте:
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!
}
… и вернемся ко второй попытке:
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.
}