我们正在将代码从C++转移到C#,并且由于对C#的了解有限,我们陷入了奇怪的境地。我们的问题是:
在c++中,我们有2-3种类型的类/结构,它们有指向属性的指针(std::string),指针的目的是确保类似对象的所有实例都指向相同的属性。e.g
struct st1{
string strVal;
};
struct st2{
string* strVal;
};
//At time of creation
st1* objst1 = new st1();
st2* objst2 = new st2();
objst2.strVal = &objst1.strVal;
//After this at all point both object will point to same value.我想要这种架构C#,我有一些建议:
请告诉我是否能在C++附近做些更好的事情。
发布于 2011-04-27 09:15:37
在C#中,所有的类都是引用/指针。因此,只要您的属性是类类型的,就可以在不同的结构中具有相同的实例。
但是当您使用字符串时,可能会出现问题。当它是类和参考属性时,它被强制为方位角。因此,当您更改它时,您不会更改实例本身,而是使用这些更改创建新副本。
想到的一个解决方案是创建自定义string类,它只包含字符串并将其用作您的类型:
public class ReferenceString
{
public String Value { get; set; }
}发布于 2011-04-27 09:31:37
您可以使用带有继承的静态属性:
class thing
{
static string stringThing;
public string StringThing
{
get { return stringThing; }
set { stringThing = value; }
}
}
class thing2 : thing
{
}然后稍后:
thing theThing = new thing();
theThing.StringThing = "hello";
thing2 theThing2 = new thing2();
// theThing2.StringThing is "hello"https://stackoverflow.com/questions/5801667
复制相似问题