0 .net c# generics static entity-framework
我有这个代码:
public class EntityMapper<T> where T : IMappingStrategy, new()
{
private static T currentStrategy;
public static T CurrentStrategy
{
get
{
if (currentStrategy == null)
currentStrategy = new T();
return currentStrategy;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
public static void Main()
{
EntityMapper<ServerMappingStrategy>.CurrentStrategy.ToString();
EntityMapper<ClientMappingStrategy>.CurrentStrategy.ToString();
EntityMapper<ServerMappingStrategy>.CurrentStrategy.ToString();
}
Run Code Online (Sandbox Code Playgroud)
好吧,问题是:
为什么我在调试时可以看到ServerBussinessMappingStrategy的构造函数只被调用一次?
这工作得很好,但我承认为什么总是EntityMapper返回我需要的正确实例,只是实例化一次ServerMappingStrategy类.
问候!
PD:对不起我的英文jeje;)
该static字段在您的持续时间内保持不变AppDomain,并在首次创建时缓存:
public static T CurrentStrategy
{
get
{
if (currentStrategy == null) // <====== first use detected
currentStrategy = new T(); // <==== so create new and cache it
return currentStrategy; // <=========== return cached value
}
}
Run Code Online (Sandbox Code Playgroud)
实际上,当它可以运行两次(或更多)时有一个边缘情况,但不太可能.
这是延迟初始化的一种非常常见的模式,并且在BCL的许多地方使用非常相同.请注意,如果它必须最多发生一次,则需要同步(lock等)或类似带静态初始化程序的嵌套类.