【发布时间】:2014-03-11 17:14:07
【问题描述】:
using System;
namespace ConsoleApplication15
{
using System.Collections.Generic;
using System.Threading;
public static class Program
{
static void Main(string[] args)
{
var test1 = new Test<List<int>>();
var t = new Thread(Tester);
t.Start();
var test2 = new Test<List<int>>();
var test3 = new Test<List<int>>();
var test4 = new Test<List<int>>();
var test5 = new Test<List<int>>();
test1.Do();
test2.Do();
test3.Do();
test4.Do();
test5.Do();
}
private static void Tester()
{
var test5 = new Test<IList<int>>();
test5.Do();
}
}
public class Test<T> where T : IEnumerable<int>
{
private static Something something;
static Test()
{
Console.WriteLine("IM static created ");
something = new Something();
Console.WriteLine(something.ToString());
}
public Test()
{
Console.WriteLine("IM created ");
}
public void Do()
{
Console.WriteLine("Do something! ");
}
}
public class Something
{
public Something()
{
Console.WriteLine("Create something");
}
}
}
当我运行上面的代码时,我期望 static Test() 中的静态构造函数会被调用一次,但是当我运行代码时,静态构造函数会被调用两次!!!!!!
当我删除这条线 <T> where T : IEnumerable<int> 一切正常(静态构造调用一次)?!!!!
【问题讨论】:
-
静态是每个 type 的,泛型类型是您指定的每个不同
T的类型。基本上,每个封闭的泛型本身就是一个类型,不管是从Test<T>定义的。 -
Test<List<int>>!=Test<IList<int>> -
@AdamHouldsworth 您应该将其发布为答案。
-
请张贴作为答案!
-
完成了,但是我的手机键盘没有格式化在线代码的字符...
标签: c#