2015-04-08 159 views
0

当前正在学习C#,而来自C++。作为B类属性的实例化对象的指针(C#)

我有一个重要的类需要跨多个类共享。示例代码在C++:

// The important class 
class Foo { 
    // ... 
} 

// Class that needs an instance of Foo 
class Bar { 
public: 
    Bar(Foo* foo); 
    // ... 

protected: 
    Foo* m_foo; // <- holds pointer to instantiated Foo-object 
} 

Bar::Bar(Foo* foo) 
    : m_foo(foo) {} 

和可能更多的类,如Bar需要知道的Foo一定实例的属性。我喜欢使用这种方法有以下几个原因:

  • 您不必手动更新m_foo不断。特别有用的是,如果有一些类可以改变它的属性和一些使用它的属性的类。它快速失控。
  • 不存在实例化的Foo的多个副本。
  • 您不必一直传递实例化的Foo作为参数。

问题:C#中是否有任何等价物可用?


什么是可能或不需要

  • 保持一个指向类的属性。换句话说,将C++代码复制到C#。关键字unsafe不适用于指向类的指针。关键字fixed只适用于身体。
  • 在每个函数中将对象作为参数传递。
  • 将更新的值更新为每个需要它的类,因此随处可见一个副本。两种内存使用效率都不高,而且会相当慢。

回答

2

如果我正确理解你的问题,你会想要做这样的事情:

 
public class Foo { 
    //... 
} 

public class Bar { 
    protected Foo m_foo; 

    //C# passes by reference for objects, so any changes to Foo would be reflected 
    //in m_foo 
    public Bar(Foo foo){ 
     m_foo = foo; 
    } 
} 

public main(){ 
    Foo foo = new Foo(); 
    Bar bar = new Bar(foo); 
    Bar bar2 = new Bar(foo); 
    foo = null; 
    //Both bar and bar2 have the same reference to foo. 
    //Any changes to foo from bar will be visible to bar2 
    //Even though foo is set to null, the object is not actually removed 
    //since both bar and bar2 have a reference to it. 
} 
+0

韦尔普,那是愚蠢的。类是一个引用类型,所以它们的属性确实从不复制......非常感谢! – Didii