2

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);
}
4

0 に答える 0