[英]C#, accessing a variable from a class?
Say i have 说我有
public int MyVariable;
in the Form1.cs file, and I want to access it from Class1.cs , what do you think would be the best way to do that? 在Form1.cs文件中,我想从Class1.cs访问它,您认为哪种方法最好呢?
Thanks! 谢谢!
base class with property: 具有属性的基类:
class Person
{
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}
}
Auto Implemented Properties (if advanced work on "name" isn't needed): 自动实施的属性 (如果不需要“名称”的高级工作):
class Person
{
public string Name { get; set; } // the Name property with hidden backing field
}
Class accessing the property: 类访问属性:
Person person = new Person();
person.Name = "Joe"; // the set accessor is invoked here
System.Console.Write(person.Name); // the get accessor is invoked here
It depends on the scenario. 这取决于场景。 But ideally, Form elements are passed to any functions that will need to use them.
但理想情况下,将Form元素传递给需要使用它们的任何函数。
You have a few options: 您有几种选择:
this
) to the class and refer to the member from that reference. this
)的引用传递给类,并从该引用中引用成员。 On a side note, you'll want to get in the habit of making your public members properties instead of variables. 附带说明一下,您将养成使您的公共成员属性代替变量的习惯。 In most cases, the property will likely just get/set the variable and nothing more.
在大多数情况下,该属性可能只会获取/设置变量,仅此而已。 However, if something more ever needs to be added it can be done so without breaking compatibility.
但是,如果需要添加更多内容,可以在不破坏兼容性的情况下进行。 Changing a variable to a property changes the footprint of the class and breaks things which use that class.
将变量更改为属性会更改类的占用空间,并且会破坏使用该类的内容。
Make the variable static
. 将变量设为
static
。 Then you can call it like Form1.MyVariable
. 然后,您可以像
Form1.MyVariable
那样调用它。
Try like this: 尝试这样:
In case (1) you can have MyClass.MyInt private readonly. 在情况(1)中,您可以将MyClass.MyInt私有只读。
public class MyForm : System.Windows.Forms.Form
{
int myInt;
public MyForm()
{
myInt = 1;
//1
var myClass = new MyClass(myInt);
//2
myClass.MyInt = myInt;
}
}
public class MyClass
{
public int MyInt { get; set; }
public MyClass(int myInt)
{
MyInt = myInt;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.