[英]Accessing class member from static method
我知道有很多討論此話題的話題,但到目前為止,我還沒有找到一個可以直接幫助我解決問題的話題。 我有需要從靜態和非靜態方法訪問的類的成員。 但是,如果成員是非靜態的,則似乎無法從靜態方法中獲取它們。
public class SomeCoolClass
{
public string Summary = "I'm telling you";
public void DoSomeMethod()
{
string myInterval = Summary + " this is what happened!";
}
public static void DoSomeOtherMethod()
{
string myInterval = Summary + " it didn't happen!";
}
}
public class MyMainClass
{
SomeCoolClass myCool = new SomeCoolClass();
myCool.DoSomeMethod();
SomeCoolClass.DoSomeOtherMethod();
}
您如何建議我從這兩種方法中獲取摘要?
您如何建議我從這兩種方法中獲取摘要?
您需要將myCool
傳遞給DoSomeOtherMethod
在這種情況下,應將其作為實例方法開始。
從根本上講,如果需要狀態實例的狀態,為什么要使其靜態?
您不能從靜態方法訪問實例成員。 靜態方法的全部要點是它們與類實例無關。
您根本無法那樣做。 靜態方法不能訪問非靜態字段。
您可以將Summary
靜態
public class SomeCoolClass
{
public static string Summary = "I'm telling you";
public void DoSomeMethod()
{
string myInterval = SomeCoolClass.Summary + " this is what happened!";
}
public static void DoSomeOtherMethod()
{
string myInterval = SomeCoolClass.Summary + " it didn't happen!";
}
}
或者,您可以將SomeCoolClass的實例傳遞給DoSomeOtherMethod並從剛剛傳遞的實例中調用Summary
:
public class SomeCoolClass
{
public string Summary = "I'm telling you";
public void DoSomeMethod()
{
string myInterval = this.Summary + " this is what happened!";
}
public static void DoSomeOtherMethod(SomeCoolClass instance)
{
string myInterval = instance.Summary + " it didn't happen!";
}
}
無論如何,我看不到您要達到的目標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.