C# 中类指针结构的使用
我们正在将代码从 C++ 转移到 C#,由于对 C# 的了解有限,我们陷入了奇怪的境地。我们的问题是:
在 C++ 中,我们有 2-3 种类型的类/结构,它们具有指向属性(std::string)的指针,指针的目的是确保相似对象的所有实例都指向相同的属性。例如,
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++ 的事情..
We are transfering our code from C++ to C# and due to limited knowledge of C# we are stuck into strange situation. Our problem is:
In c++ we have 2-3 types of class/structures which have pointers to property (std::string), purpose of pointer is to make sure that all the instance for similar object will point to same property. 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.
I want this kind of architecture C#, I got some suggestion like:
- Declare events
- Make code unsafe and use pointers (but I think this will lead to some other problems)
Please let me know if something better and near to C++ can be done here..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 C# 中,所有类都是引用/指针。因此,只要您的属性是类类型,您就可以在不同的结构中拥有相同的实例。
但是当你使用字符串时就会出现问题。虽然它是类和引用属性,但它被强制是不可变的。因此,当您更改它时,您不会更改实例本身,而是会使用这些更改创建新副本。
我想到的一种解决方案是创建自定义字符串类,该类仅包含字符串并将其用作您的类型:
In C# all clases are references / pointers. So as long as your property is of class type, you can have same instance in different structures.
But problem can arise when you use string. While it is class and reference property, it is enforced to be imutable. So when you change it, you dont change the instance itself, but you create new copy with those changes.
One solution that comes to mind is to create custom string class, that will simply contain string and use it as your type:
您可以使用带有继承的静态属性:
然后:
You could use a static property with inheritance:
Then later: