目前正在学习来自C ++的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#中是否有可用的等效内容?
什么是不可能或不受欢迎:
unsafe
不适用于指向类的指针。关键字fixed
仅适用于正文。答案 0 :(得分: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. }