关于 static T 的一个问题
private static T instance = null;
public static T Instance
{
get
{
if (instance == null)
instance = new T();
return instance;
}
}
如上面代码,如果某个类中有这样一个静态的T的变量 private static T instance = null; ,请问是否传入N个不同类型的T,就会N个不同的静态实例?
比如,先传入一个string类型,就会有一个静态的 string instance
在传入一个int类型,就会有一个静态的 int instance
--------------------编程问答-------------------- 就一个就一个 --------------------编程问答--------------------
写了个小测试,应该是N个实例
测试层数如下:
class Program
{
static void Main(string[] args)
{
DAO1 D1 = DAO1.Instance;
DAO2 D2 = DAO2.Instance;
DAO1 D4 = DAO1.Instance;
DAO2 D5 = DAO2.Instance;
Console.ReadKey();
}
}
public class DAO1 : BaseDAO<DAO1>
{
}
public class DAO2 : BaseDAO<DAO2>
{
}
public class BaseDAO<T> where T : BaseDAO<T>, new()
{
private static T instance = null;
public static T Instance
{
get
{
if (instance == null)
{
Console.WriteLine(typeof(T) + "类型instance为null,为其初始化。");
instance = new T();
}
else
{
Console.WriteLine(typeof(T) + "类型instance不为null,直接返回。");
}
return instance;
}
}
}
输出:
--------------------编程问答-------------------- 这里
StaticTTest.DAO1类型instance为null,为其初始化。
StaticTTest.DAO2类型instance为null,为其初始化。
StaticTTest.DAO1类型instance不为null,直接返回。
StaticTTest.DAO2类型instance不为null,直接返回。
应该是一个啊从你这个测试结果来看,这个不是单例模式的 饿汉模式么 --------------------编程问答-------------------- 就一个哦,不同用户都在改变这个值,所以如果需要针对不同用户 的变量,不能设static,否则造成混乱。 --------------------编程问答-------------------- 根据不同t
泛型是不同的类
--------------------编程问答-------------------- 你 测试一下 、传个 String 的 和传个 int 的看看。 、 --------------------编程问答--------------------
string,int能传么。又不是对象
补充:.NET技术 , ASP.NET