简体   繁体   中英

Pointer to instantiated object as property of class B (C#)

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:

  • You don't have to manually update 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.
  • No multiple copies of an instantiated Foo present.
  • You don't have to pass the instantiated Foo as an argument all the time.

Question : Are there any equivalents available in C#?


What is not possible or undesired :

  • Keeping a pointer to a class as property. In other words, copying the C++ code to C#. The keyword unsafe does not apply to pointers to classes. The keyword fixed only works inside bodies.
  • Passing the object as argument in every single function.
  • Updating the newer values to every single class that need it and consequently having a copy lying around everywhere. Not efficient for both memory usage and will be considerably slower.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM