当前位置: 动力学知识库 > 问答 > 编程问答 >

Why can't I reference a static member from an inner class in C#?

问题描述:

I have a static class

namespace MyNameSpace{

public static class MyStaticClass {

public static string myStaticMember = "";

}

}

I can reference myStaticMember in another class like this:

string varString = MyStaticClass.myStaticMember;

except if MyStaticClass is an inner class of the other class.

Why ?

Update: this is what I'd like to do

using System;

namespace test

{

public class MyOuterClass

{

public static class MyStaticClass

{

public static string myStaticMember = "";

}

MyStaticClass.myStaticMember = "Hello";

}

}

网友答案:

In this case you need to reference it through the outer class:

string varString = MyOuterClass.MyStaticClass.myStaticMember

UPDATE:

The code you've posted won't compile because you are trying to access a field directly inside the outer class, every statement should be contained inside a method, you need to declare a method in the outer class in which you could access the inner class field.

using System;
public class Program
{
    public static class MyStaticClass
    {
        public static string myStaticMember = "";
    }

    static void Main()
    {
        MyStaticClass.myStaticMember = "Hello";
        Console.WriteLine(MyStaticClass.myStaticMember);
    }
}
网友答案:
        MyStaticClass.myStaticMember = "Hello";

That's an assignment statement, not a declaration. Statements must be written inside a method. A suitable one would be the constructor for MyOuterClass:

    public MyOuterClass() {
        MyStaticClass.myStaticMember = "Hello";
    }
分享给朋友:
您可能感兴趣的文章:
随机阅读: