从其他名称空间访问变量 [英] Accessing variables from other namespaces
问题描述
我是C#和编程的新手,我的问题是如何调用位于不同命名空间中的变量?如果我有此代码
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
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;}
}
}
这篇关于从其他名称空间访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!