C# 从静态方法访问类成员
我知道有很多帖子都在谈论这个问题,但到目前为止,我还没有找到一个能直接帮助我解决问题的帖子。我需要从静态和非静态方法访问类的成员。但是如果成员是非静态的,我似乎无法通过静态方法访问它们C# 从静态方法访问类成员,c#,asp.net,static,non-static,C#,Asp.net,Static,Non Static,我知道有很多帖子都在谈论这个问题,但到目前为止,我还没有找到一个能直接帮助我解决问题的帖子。我需要从静态和非静态方法访问类的成员。但是如果成员是非静态的,我似乎无法通过静态方法访问它们 public class SomeCoolClass { public string Summary = "I'm telling you"; public void DoSomeMethod() { string myInterval = Summary + " thi
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
——在这种情况下,您应该首先将其作为实例方法
从根本上说,如果它需要该类型实例的状态,为什么要将其设置为静态呢?您不能这样做。静态方法无法访问非静态字段 您可以使
摘要
静态
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!";
}
}
无论如何,我看不出您想要达到的目标。静态成员属于该类型,而非静态成员属于该类型的实例。是否需要
Summary
保持不变?您可以标记ispublic const string Summary
,并且可以从这两个站点访问它。感谢各位提供的建设性建议。在我提交了问题并准备去吃午饭后,我意识到,如果我将DoSomeOtherMethod作为一个实例方法并使用它,那就省去了一些麻烦。