在C#中,我有一些通用功能。我有一个动态对象列表,我想用它来调用正确类型的函数
它在简单的情况下工作,但是一旦模板嵌套就不能编译。
如何使它在嵌套模板中工作?
void f1<T>(T a )
{
Console.WriteLine( typeof(T) );
}
void f2<T>(List<T> a )
{
Console.WriteLine( typeof(T) );
}
void f3<T>(List<List<T>> a )
{
Console.WriteLine( typeof(T) );
}
[Test ()]
public void TestDynamic()
{
var l = new List<dynamic>();
l.Add(3);
l.Add("hello");
//This compiles and works fine
foreach (var i in l)
f1(i);
//prints System.Int32
//prints System.String
var l2 = new List<dynamic>();
l2.Add(new List<int>{3});
l2.Add(new List<string>{"hello" } );
//This compiles and works fine
foreach (var i in l2)
f2(i);
//prints System.Int32
//prints System.String
var l3 = new List<dynamic>();
l3.Add(new List<List<int>>{new List<int>{3} });
l3.Add(new List<List<string>> {new List<string>{"hello" } });
//This doesn't compile : "The type argument for method f3 cannot be inferred from the usage, try specifying the type arguments explicitly
foreach (var i in l3)
f3(i);
}