[英]C# How can I acces the same variable in mutliple classes
I'm working on my third C# program and I'm having a hard time. 我正在开发我的第三个C#程序,现在很难。 I don't get how I can access a variable in multiple classes :
我不知道如何访问多个类中的变量:
This is a slider to control the size of the shape I'm drawing 这是一个滑块,用于控制我正在绘制的形状的大小
public void trackBar1_Scroll(object sender, EventArgs e)
{
int slider = (int)trackBar1.Value ;
}
public void DrawCar ()
{
drawArea = drawingArea.CreateGraphics();
Pen blackpen = new Pen(Color.Orange);
drawArea.DrawLine(blackpen, slider , 10, 500, 500);
drawArea.DrawArc(Pens.Orange, new Rectangle( 10 , 10, 100, 100), 50, 100);
}
I need to access the "slider" value to control the size of the car. 我需要访问“滑块”值来控制汽车的尺寸。
If you want to access it in the same class, but multiple methods, you can make that as a member variable of the class. 如果要在同一个类中使用多个方法访问它,则可以将其作为该类的成员变量。
public class YourClass
{
private int sliderValue=0;
public void MethodA()
{
sliderValue=12;
}
public void MethodB()
{
var localValue=sliderValue+10;
}
}
If you want the value across multiple classes, you might consider creating a singleton class and add the properties you want to that. 如果要跨多个类使用该值,则可以考虑创建一个单例类并向其中添加所需的属性。
Add a property to your class that contains trackBar1 like this: 将这样的属性添加到包含trackBar1的类中,如下所示:
public int Slider { get { return this.trackBar1.Value; } }
Then you can access the slider value outside on the class where the trackBar1 is defined from instances of that class. 然后,您可以在从该类的实例定义trackBar1的类的外部访问滑块值。
the best thing you can achieve to get access is this way or start using mvvm pattern and defining properties, that will make things lot easier: 获得访问权限的最佳方法就是这种方式,或者开始使用mvvm模式并定义属性,这将使事情变得容易得多:
public static int slider;
public void trackBar1_Scroll(object sender, EventArgs e)
{
slider = (int)trackBar1.Value ;
}
public void DrawCar ()
{
drawArea = drawingArea.CreateGraphics();
Pen blackpen = new Pen(Color.Orange);
drawArea.DrawLine(blackpen, slider , 10, 500, 500);
drawArea.DrawArc(Pens.Orange, new Rectangle( 10 , 10, 100, 100), 50, 100);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.