为什么我的价值观不被保留一个类型的实例之间? [英] Why are my values not being kept between instances of a type?
问题描述
我有类:
public class pro {
private string url = string.Empty;
public string GetURL() { return url; }
public void SetURL(string value) { url = value; }
}
在这行我得到值:
string url = li1.Value;
pro itm = new pro(); // I have create Proprtie so I'm calling that
itm.SetURL(url); // here I'm setting value
再后来:
pro itm = new pro(); //properties object I have created
string url = itm.GetURL(); // I'm not getting value which I have set in first
类。
我有企业的性质创建还;我究竟做错了什么?
I have create Proprties also; what am I doing wrong?
推荐答案
每一个类实例(即每新款Pro()
)有不同的实例值;它完美地预计,如果你有2个不同的实例,那么他们将不会分享网址
,例如。如果你想分享这一点,你应该在相同 亲
实例可以在两个地方,通过传递亲
左右。
Every class instance (i.e. every new pro()
) has different instance values; it is perfectly expected that if you have 2 different instances, then they will not share a URL
, for example. If you want to share this, you should make the same pro
instance available to both places, by passing the pro
around.
顺便说一句,的GetURL()
/ SetURL()
不是地道的C# - 这将是更为常见的有一个的属性的,即
Incidentally, GetURL()
/ SetURL()
is not idiomatic C# - it would be more common to have a property, i.e.
public string Url {get;set;}
您会然后访问为:
which you would then access as:
YourType item = new YourType();
item.Url = "http://foo.com/bar/";
// ...
string url = item.Url;
从注释,它的声音的就像你正在谈论静态
的数据;我要强调的是,使用静态
这通常不是一个好主意,并可能导致大量的与测试,多租户,线程等问题;但是:下列作品无任何实例:
From the comments, it sounds like you are talking about static
data; I should emphasise that using static
for this is not usually a good idea, and can lead to lots of problems with testing, multi-tenancy, threading, etc; but: the following works without any instances:
public class Properties {
public static string Url {get;set;}
}
...
Properties.Url = "http://foo.com/bar/";
...
string url = Properties.Url;
请注意:完全没有实例
然而,它几乎总是preferable简单地保持一个的实例可用,并用实例属性针对常见的实例。
However, it is almost always preferable to simply keep an instance available, and use instance properties against that common instance.
这篇关于为什么我的价值观不被保留一个类型的实例之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!