范围解析c#中的运算符访问全局变量?

时间:2013-03-31 07:40:22

标签: c# .net

我有一个C ++程序

int x=100; //Global declaration
main()
{
    int x=200;
    {
        int y;
        y=x;
        cout<<"Inner Block"<<endl;
        cout<<x<<endl;
        cout<<y<<endl
        cout<<::x<<endl;
    }
    cout<<"Outer Block"<<"\n";
    cout<<x<<"\n";
    cout<<::x;
}

该计划的输出是: 内胎 200 200 100 外块 200 100

我想在c#中尝试类似的东西但是当我输入:: x时,我给了我错误... 请帮忙

我试过的是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CAScopeResolution_Operator
{
    class Program
    {
        static int x = 100;
        static void Main(string[] args)
        {
            int x = 200;
            {
                int y;
                y = x;
                Console.WriteLine("Inner Block");
                Console.WriteLine(x);
                Console.WriteLine(y);
                Console.WriteLine(Program.x);  
            }
            Console.WriteLine("Outer Block");
            Console.WriteLine(x);
            Console.WriteLine(Program.x);
            Console.ReadLine(); 
        }
    }
}

我已声明静态x,但我不认为这是c#中类似代码的解决方案...请帮忙

1 个答案:

答案 0 :(得分:3)

由于C#不像C++那样处理全局变量::具有不同的含义。这是关于名称空间的,因为您可以通过它所属的类来识别每个成员 因此,如果您具有共享标识符但位于不同命名空间的名称空间和/或类型,则可以使用:: - 运算符来标识它们。

using colAlias = System.Collections;
namespace System
{
class TestClass
{
    static void Main()
    {
        // Searching the alias:
        colAlias::Hashtable test = new colAlias::Hashtable();

        // Add items to the table.
        test.Add("A", "1");
        test.Add("B", "2");
        test.Add("C", "3");

        foreach (string name in test.Keys)
        {
            // Searching the global namespace:
            global::System.Console.WriteLine(name + " " + test[name]);
        }
    }
}
}

生成此

A 1
B 2
C 3

有关MSDN参考,请参阅here

相关问题