Is there a way to use a variable in multiple classes in C#?
If I define a variable in one class file, is开发者_JAVA技巧 there a way to access the same variable in another class?
class Class1
{
static const int myInteger = 256;
}
class Class2
{
private void myMethod()
{
int i = Class1.myInteger;
//i is now 256.
}
}
You can declare the variable as static at the topmost scope of your first class (Class1). See the MSDN article for more information regarding static
members:
http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx
Yes, if you have a reference to an object of the first class. Or if that variable is a public static member of the first class, in which case you don't need am object reference.
Yes, provide access to it via a Property.
http://msdn.microsoft.com/en-us/library/x9fsa0sw%28v=VS.71%29.aspx
Variables should be exposed as public properties or fields if you want to access them through other classes. However these classes need a relationship.
public class C1
{
public int x = 1;
}
public class C2
{
private C1 otherClass;
// constructor
public C2(C1 other)
{
this.otherClass = other;
}
public void accessOtherClass()
{
Console.WriteLine(this.otherClass.x);
}
}
精彩评论