【问题标题】:C# Constructor returning pointer on other objectC#构造函数返回其他对象的指针
【发布时间】:2015-06-03 01:36:44
【问题描述】:

我想知道构造函数是否有可能从同一个类中返回一个已经实例化的对象的指针? 例如:

    Class Example
    {
            private static Example A = null

            public Example()
            {
                    if (RefTrace == null)
                    {
                            //Here is the initialization of all attributes
                             A = this;
                    }
                      else
                            return A; //To return pointer on already existing instance.
            }


    }

编辑: 这只是想法,我知道它不起作用。但是我想知道是否有办法实现这一点?

【问题讨论】:

  • 何不亲自试一试?
  • 我试了,还是不行。这只是为了说明我为什么要努力实现
  • 构造函数不返回任何东西。
  • 你可以有这样的东西 - 在 Javascript 中;) - 在 C# 中,构造函数会为你创建一个新对象,但显而易见的解决方案是编写一个静态方法;)
  • 如何将构造函数设为私有并使用像public static Example GetExample() 这样的公共静态方法,在其中放置“决定是否应实例化新对象或应返回存储值”逻辑?

标签: c# pointers object constructor


【解决方案1】:

你试图实现的是一个 Singleton 对象。您可以在此处阅读有关单例模式的信息:https://msdn.microsoft.com/en-us/library/ff650316.aspx

示例代码:

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get 
     {
        if (instance == null)
      {
         instance = new Singleton();
      }
     return instance;
    }
  }

}

【讨论】:

  • 不需要那种愚蠢的检查,这就是静态构造函数的用途。我们已经过去了十二年或两年的美好 C++ 时代!
  • 还有一些人(包括我在内)将 Singleton 视为一种反模式 (here is a nice example)
【解决方案2】:

C# language specification 5.0 上面写着:

构造函数被声明为没有返回类型且与包含类同名的方法。

其他问题/答案中也提到了这一点,即:Are class constructors void by default?

正如该线程中已经提到的,您似乎正在尝试使用单例模式。 Jon Skeet 在各种变体上都有一个 good blog post - 我更喜欢他的 Lazy<T> 实现。

【讨论】:

  • 我去看看,我缺少术语。辛格尔顿确实是我想要的。谢谢
猜你喜欢
  • 2020-06-15
  • 2022-11-30
  • 2011-02-09
  • 1970-01-01
  • 1970-01-01
  • 2013-03-07
  • 2015-11-19
  • 2022-11-07
相关资源
最近更新 更多