如何从其他应用程序层中找到对象的实例。我必须使用我的模型视图从DAL刷新一个属性。这是完成任务的最简单方法。有可能的? 我的意思是:
SomeClass someClass = FindAllredyConstructedInstance(SomeClass);
请求帮助。
答案 0 :(得分:0)
我想要做的就是创建一个单例对象。这是它最简单的形式。
public class SomeClass
{
//single instance used everywhere.
private static SomeClass _instance;
//private constructor so only the GetInstance() method can create an instance of this object.
private SomeClass()
{
}
//get single instance
public static SomeClass GetInstance()
{
if (_instance != null) return _instance;
return _instance = new SomeClass();
}
}
现在要访问对象的同一个实例,只需调用
即可SomeClass singleton = SomeClass.GetInstance();
如果你想使用更高级的技术,那么你可以考虑使用像依赖注入这样的东西,但这是一个不同的讨论。
编辑:
public class SomeClass
{
private static SomeClass _instance;
private SomeClass()
{
}
public static SomeClass GetInstance()
{
if (_instance == null)
throw new Exception("Call SetInstance() with a valid object");
return _instance;
}
public static void SetInstance(SomeClass obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
_instance = obj;
}
}
答案 1 :(得分:0)
我解决了我的问题:
SomeClass instance = ServiceLocator.Current.GetInstance<SomeClass>();