C# 在不同的 class/file 中使用实例化 class
C# Use instantiated class in a different class/file
我是否可以在另一个 class 和文件中使用一次 class 的实例而无需重新实例化它?
class Start
{
public static Log Log = new Log(...);
}
class Start1
{
Log.Write("New instance!");
}
我读过有关必须使用 get/set
块来执行此操作的信息,但我不确定我将如何处理,
单例模式:
public class Log
{
private static Log instance;
private Log() { }
public static Log Instance
{
get
{
return instance ?? (instance = new Log());
}
}
}
通过调用Log.Instance来使用它,依此类推。
要使用参数调用它,您需要执行如下操作:
public class Log
{
private string foo;
private static Log instance;
public static Log Instance
{
get
{
if (instance == null)
{
throw new InvalidOperationException("Call CreateInstance(-) to create this object");
}
else
{
return instance;
}
}
}
private Log(string foo) { this.foo = foo; }
public static Log CreateInstance(string foo)
{
return instance ?? (instance = new Log(foo));
}
}
但是,在这个庄园中使用单例通常不是一个好主意。看看依赖注入/控制反转,看看如何解决这个问题。
我是否可以在另一个 class 和文件中使用一次 class 的实例而无需重新实例化它?
class Start
{
public static Log Log = new Log(...);
}
class Start1
{
Log.Write("New instance!");
}
我读过有关必须使用 get/set
块来执行此操作的信息,但我不确定我将如何处理,
单例模式:
public class Log
{
private static Log instance;
private Log() { }
public static Log Instance
{
get
{
return instance ?? (instance = new Log());
}
}
}
通过调用Log.Instance来使用它,依此类推。
要使用参数调用它,您需要执行如下操作:
public class Log
{
private string foo;
private static Log instance;
public static Log Instance
{
get
{
if (instance == null)
{
throw new InvalidOperationException("Call CreateInstance(-) to create this object");
}
else
{
return instance;
}
}
}
private Log(string foo) { this.foo = foo; }
public static Log CreateInstance(string foo)
{
return instance ?? (instance = new Log(foo));
}
}
但是,在这个庄园中使用单例通常不是一个好主意。看看依赖注入/控制反转,看看如何解决这个问题。