[英]Accessing variables from other namespaces
I am new to C# and programming in general my question is how do you call a variable that is in a different namespace?我是 C# 新手,一般来说我的问题是如何调用不同命名空间中的变量? if I have this code如果我有这个代码
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?我正在传入服务名称,我将如何从不同的命名空间调用一个或多个变量值?
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;}
}
}
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
As a side node, it can be done by adding reference to the assembly in which the public
members of another assembly are used.作为侧节点,可以通过添加对使用另一个程序集的public
成员的程序集的引用来完成。 That's what incurred me.这就是我招致的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.