从静态方法访问类成员

5
我知道有很多关于这个问题的帖子,但到目前为止我还没有找到一个能直接帮助我的情况。 我需要从静态和非静态方法中访问类的成员。 但是,如果成员是非静态的,我似乎无法从静态方法中访问它们。
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();
}

您建议我如何从这两种方法中获取摘要?


1
静态成员属于“类型”,非静态成员属于“该类型的实例”。 - asawyer
1
你需要将 Summary 设为常量吗?你可以将其标记为 public const string Summary,这样你就可以从两个地方访问它了。 - Justin Skiles
3个回答

9

无论使用哪种方法,你会建议我如何获取摘要?

您需要将 myCool 传递给 DoSomeOtherMethod —— 在这种情况下,您应该首先将其作为实例方法。

从根本上讲,如果它需要该类型的实例的状态,为什么要将其设置为静态?


谢谢大家的建设性意见。我在提交问题后去吃午饭时意识到,如果我将DoSomeOtherMethod变成实例方法,这将为我节省一些麻烦。 - Jeremy

7

你无法从静态方法访问实例成员。静态方法的整个意义在于它们与类实例无关。


2
你不能那样做。静态方法无法访问非静态字段。
你可以将 "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!";
    }
}

无论如何,我真的看不到你试图达到的目标。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接