JMK*_*JMK 2 c# properties class
如果我创建一个新类,并在这个类中我放了一个这样的属性:
public class CurrentDirectory
{
private string cd;
public string CurrentDirectory
{
get
{
return cd;
}
set
{
cd = value;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我在程序中的某一点创建了这个类的新实例,如下所示:
CurrentDirectory myCurrentDirectory = New CurrentDirectory();
Run Code Online (Sandbox Code Playgroud)
然后我像这样设置一个值到CurrentDirectory:
myCurrentDirectory.CurrentDirectory = @"C:\MyFiles\Here";
Run Code Online (Sandbox Code Playgroud)
然后,在我的程序的另一个点上,我创建了另一个CurrentDirectory实例,并像这样"获取"CurrentDirectory的值:
CurrentDirectory myCurrentDirectory1 = new CurrentDirectory();
string putFilesHere = myCurrentDirectory1.CurrentDirectory;
Run Code Online (Sandbox Code Playgroud)
这会返回我之前设置的值,还是需要在同一个实例中"获取"并"设置"我的值?
谢谢
不,这不会以这种方式保存值,仅仅将一个用户的名称设置为"Heisenburg"会影响我的名字"Anthony Pegram".类的每个实例都是不同的对象,并且实例属性和一个实例的成员不会转移到其他实例.
User user = new User(); // this is my object!
user.Name = "Anthony Pegram"; // this is my name!
User otherUser = new User(); // this is your object!
otherUser.Name = "Heisenburg"; // this is your name!
// my object is not your object
Run Code Online (Sandbox Code Playgroud)
如果您需要将属性共享到其他位置看到您在其他位置设置的相同值的位置,则需要共享实例,或者通过属性上的关键字使数据本身共享static.
class Foo
{
public static string Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如果使用静态,则状态变为全局,并且不依赖于特定实例.事实上,它不需要实例.您只需直接通过类名访问它,而不是通过该类的对象访问它.
Foo.Bar = "Blah"; // no instance necessary
string data = Foo.Bar;
Run Code Online (Sandbox Code Playgroud)