Currently learning C# while coming from C++.
I have an important class that needs to be shared across multiple classes. Example code in 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) {}
And possibly more classes such as Bar
that need to know the properties of a certain instance of Foo
. I like using this method for several reasons:
m_foo
constantly. Especially helpful if there are a number of classes that change its properties and a number of classes that use its properties. It gets out of control real fast. Foo
present. Foo
as an argument all the time. Question : Are there any equivalents available in C#?
What is not possible or undesired :
unsafe
does not apply to pointers to classes. The keyword fixed
only works inside bodies. If I understand your question correctly, you would want to do something like this:
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. }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.