开发者

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";
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜