c#中类似指针结构的使用

本文关键字:结构 指针 | 更新日期: 2023-09-27 17:53:48

我们正在将我们的代码从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#架构,我得到了一些建议:

    <
  1. 声明事件/gh>
  2. 使代码不安全并使用指针(但我认为这会导致一些其他问题)

请让我知道如果有更好的和接近c++的东西可以在这里完成。

c#中类似指针结构的使用

在c#中所有的类都是引用/指针。所以只要你的属性是类类型的,你就可以在不同的结构中拥有相同的实例。

但是当您使用string时可能会出现问题。虽然它是类和引用属性,但它被强制为不可变的。所以当你改变它的时候,你不会改变实例本身,而是创建一个新的副本。

我想到的一个解决方案是创建自定义字符串类,它将简单地包含字符串并使用它作为您的类型:

public class ReferenceString
{
    public String Value { get; set; }
}

您可以使用带有继承的静态属性:

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"