C#构造函数在其他对象上返回指针
C# Constructor returning pointer on other object
我想知道构造函数是否有可能 return 已实例化对象上的指针形成相同的 class?
例如:
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.
}
}
编辑:
这只是想法,我知道它行不通。但是我想知道有没有办法实现这个?
您要实现的是单例对象。您可以在此处阅读有关单例模式的信息: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# language specification 5.0 它说:
A constructor is declared like a method with no return type and the same name as the containing class.
这个在其他question/answers中也有提到,即:Are class constructors void by default?
如本帖中所述,您似乎正在尝试使用单例模式。 Jon Skeet 在各种变体上都有 good blog post - 我更喜欢他的 Lazy<T>
.
实现
我想知道构造函数是否有可能 return 已实例化对象上的指针形成相同的 class? 例如:
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.
}
}
编辑: 这只是想法,我知道它行不通。但是我想知道有没有办法实现这个?
您要实现的是单例对象。您可以在此处阅读有关单例模式的信息: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# language specification 5.0 它说:
A constructor is declared like a method with no return type and the same name as the containing class.
这个在其他question/answers中也有提到,即:Are class constructors void by default?
如本帖中所述,您似乎正在尝试使用单例模式。 Jon Skeet 在各种变体上都有 good blog post - 我更喜欢他的 Lazy<T>
.