存储对对象的引用 [英] Store a reference to an object

查看:128
本文介绍了存储对对象的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个奇怪的问题,但我想知道任何人可以帮助...

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

在C ++中,我可以这样做

In C++, I could do something like this

class MyOtherClass
{
     private:
         MyLogger* logger;
     public:
         MyOtherClass (MyLogger* logger)
              : logger (logger)
         {}
};

class MyClass
{
     private:
         MyLogger* logger;
     public:
         MyClass (MyLogger* logger)
              : logger (logger)
         {}
};

int main (int c, char** args)
{
    MyLogger* logger = new MyLogger ();
    /* Code to set up logger */
    MyOtherClass* myOtherClass = new MyOtherClass (logger);
    MyClass* myClass = new MyClass (logger);
}

这样每个其他对象(myOtherClass和myClass)到记录器,所以他们将调用相同的logger类。但是,我将如何在C#中实现同样的事情?有办法存储一个引用或指向一个全局对象的指针 - 我猜C#如果我做一些像

So that each of the other objects (myOtherClass and myClass) would contain a pointer to logger, so they would be calling the same logger class. However, how would I achieve the same thing in C#? Is there a way to store a reference or pointer to a global object - I'm guessing that in C# if I do something like

public class MyClass
{
     private MyLogger logger = null;

     public MyClass (MyLogger _logger)
     {
         logger = _logger;
     }
};

它实际上将类变量记录器分配给_logger的副本?或者我正在混合的东西:S

that its actually assigning the class variable logger to a copy of _logger? Or am I'm mixing things up :S

任何帮助是非常感谢,并提前感谢!

Any help is very much appreciated, and thank you in advance!

推荐答案

实际上在C#中更简单。

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);

在C#中,类基本上都是作为引用(真正只是引用下的指针)。在此代码段中,您将引用传递给 logger 到这两个对象的构造函数。这个引用是一样的,所以每个实例都有相同的 MyLogger 实例。

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.

很多只需要删除指针syntax = D

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

这篇关于存储对对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆