从静态方法访问类成员 [英] Accessing class member from static method
问题描述
我知道有很多的线程在谈论这一点,但到目前为止,我还没有找到一个直接帮助我的情况。我有类的成员,我需要从静态和非静态方法来访问。但是,如果成员都是非静态的,我似乎无法从静态方法得到他们。
公共类SomeCoolClass
{
公共字符串摘要=我要告诉你; 公共无效DoSomeMethod()
{
字符串myInterval =摘要+,这是发生了什么事!
} 公共静态无效DoSomeOtherMethod()
{
字符串myInterval =摘要+它没有发生!
}
}公共类MyMainClass
{
SomeCoolClass myCool =新SomeCoolClass();
myCool.DoSomeMethod(); SomeCoolClass.DoSomeOtherMethod();
}
你会如何建议我从任一类型的方法得到总结?
你会如何建议我从任一类型的方法得到总结?
块引用>您需要通过
myCool
到DoSomeOtherMethod
- 在这种情况下,你应该让一个实例方法下手。从根本上来说,如果它需要的类型的实例的状态,为什么你会使其静态的?
I know there are a lot of threads talking about this but so far I haven't found one that helps my situation directly. I have members of the class that I need to access from both static and non-static methods. But if the members are non-static, I can't seem to get to them from the static methods.
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(); }
How would you suggest I get Summary from either type of method?
解决方案How would you suggest I get Summary from either type of method?
You'll need to pass
myCool
toDoSomeOtherMethod
- in which case you should make it an instance method to start with.Fundamentally, if it needs the state of an instance of the type, why would you make it static?
这篇关于从静态方法访问类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!