C# 从其他命名空间访问变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/740937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:21:16  来源:igfitidea点击:

Accessing variables from other namespaces

c#variablesnamespaces

提问by Adonis L

I am new to C# and programming in general my question is how do you call a variable that is in a different namespace? if I have this code

我是 C# 新手,一般来说我的问题是如何调用不同命名空间中的变量?如果我有这个代码

public void servicevalues(string _servicename)
{
  string servicename = _servicename;
  string query = string.Format("SELECT * FROM Win32_Service WHERE Name ='{0}'", servicename);
  ManagementObjectSearcher moquery = new ManagementObjectSearcher(query);
  ManagementObjectCollection queryCollection = moquery.Get();
  foreach (ManagementObject service in queryCollection)
  {
    string serviceId = Convert.ToString(service["DisplayName"]);
    bool serviceResult = Convert.ToBoolean(service["Started"]);
  }

and I am passing in service name how would I call one or multiple variable values from a different namespace?

我正在传入服务名称,我将如何从不同的命名空间调用一个或多个变量值?

采纳答案by Andy White

Normally, variables don't live in a namespace alone, they live inside another class that could be in another namespace. If you need to access a variable in another class (in another namespace), your other class needs to expose the variable somehow. The common practice for this is to use a public Property (static if you only need access to that variable) for the variable.

通常,变量不会单独存在于命名空间中,它们存在于可能位于另一个命名空间中的另一个类中。如果您需要访问另一个类(在另一个命名空间中)中的变量,则您的另一个类需要以某种方式公开该变量。对此的常见做法是为变量使用公共属性(如果您只需要访问该变量,则为静态属性)。

namespace My.Namespace
{
    public class MyClassA
    {
        public void MyMethod()
        {
            // Use value from MyOtherClass
            int myValue = My.Other.Namespace.MyOtherClass.MyInt;
        }
    }
}

namespace My.Other.Namespace
{
    public class MyOtherClass
    {
        private static int myInt;
        public static int MyInt
        {
            get {return myInt;}
            set {myInt = value;}
        }

        // Can also do this in C#3.0
        public static int MyOtherInt {get;set;}
    }
}

回答by heartlandcoder

To add to Andy's answer you can also shorten the call to the MyInt property by adding this above the My.Namespace declaration:

要添加到安迪的答案中,您还可以通过在 My.Namespace 声明上方添加以下内容来缩短对 MyInt 属性的调用:

using My.Other.Namespace

If you do that then your call to the MyInt property would look like this:

如果您这样做,那么您对 ​​MyInt 属性的调用将如下所示:

int MyValue = MyOtherClass.MyInt

回答by snr

As a side node, it can be done by adding reference to the assembly in which the publicmembers of another assembly are used. That's what incurred me.

作为侧节点,可以通过添加对public使用另一个程序集成员的程序集的引用来完成。这就是我招致的。