Store a reference to an object

前端 未结 4 1354
庸人自扰
庸人自扰 2021-01-04 13:59

A bit of a weird question but I was wondering anyone could help...

In C++, I could do something like this

class MyOtherClass
{
     private:
                 


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-04 15:02

    It's actually a lot simpler in C#.

    Basically, you can do this:

    MyLogger logger = new MyLogger();
    MyOtherClass myOtherClass = new MyOtherClass(logger);
    MyClass myClass = new MyClass(logger);
    

    In C#, the classes are basically kept around as references (really just pointers under the hood). In this snippet, you are passing the reference to logger to the constructors of both objects. That reference is the same, so each instance has the same MyLogger instance.

    In this particular instance, you pretty much just need to remove the pointer syntax =D

提交回复
热议问题