首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类指针结构在C#中的应用

类指针结构在C#中的应用
EN

Stack Overflow用户
提问于 2011-04-27 09:05:21
回答 2查看 439关注 0票数 0

我们正在将代码从C++转移到C#,并且由于对C#的了解有限,我们陷入了奇怪的境地。我们的问题是:

在c++中,我们有2-3种类型的类/结构,它们有指向属性的指针(std::string),指针的目的是确保类似对象的所有实例都指向相同的属性。e.g

代码语言:javascript
复制
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. 声明事件
  2. 使代码不安全并使用指针(但我认为这会导致一些其他问题)

请告诉我是否能在C++附近做些更好的事情。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-04-27 09:15:37

在C#中,所有的类都是引用/指针。因此,只要您的属性是类类型的,就可以在不同的结构中具有相同的实例。

但是当您使用字符串时,可能会出现问题。当它是类和参考属性时,它被强制为方位角。因此,当您更改它时,您不会更改实例本身,而是使用这些更改创建新副本。

想到的一个解决方案是创建自定义string类,它只包含字符串并将其用作您的类型:

代码语言:javascript
复制
public class ReferenceString
{
    public String Value { get; set; }
}
票数 3
EN

Stack Overflow用户

发布于 2011-04-27 09:31:37

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

代码语言:javascript
复制
class thing
{
  static string stringThing;
  public string StringThing
  {
    get { return stringThing; }
    set { stringThing = value; }
  }
}

class thing2 : thing
{
}

然后稍后:

代码语言:javascript
复制
thing theThing = new thing();
theThing.StringThing = "hello";

thing2 theThing2 = new thing2();
// theThing2.StringThing is "hello"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5801667

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档