我对以下代码有一个非常奇怪的问题:
using System;
using System.Linq;
namespace ConsoleApp1
{
public class Program
{
public static void Main(string[] args)
{
var testTuples1 = GimeStringTuples("foo", "bar");
var testTuples2 = GimeTuples("foo", "bar");
Console.ReadKey();
}
public static object GimeStringTuples(params string[] values)
{
Type genericType = Type.GetType("System.Tuple`" + values.Length);
Type[] typeArgs = values.Select(_ => typeof(string)).ToArray();
Type specificType = genericType.MakeGenericType(typeArgs);
return Activator.CreateInstance(specificType, values);
}
public static object GimeTuples<T>(params T[] values)
{
Type genericType = Type.GetType("System.Tuple`" + values.Length);
Type[] typeArgs = values.Select(_ => typeof(T)).ToArray();
Type specificType = genericType.MakeGenericType(typeArgs);
dynamic result;
string[] testArgs = { "foo", "bar" };
result = Activator.CreateInstance(specificType, testArgs);
result = Activator.CreateInstance(specificType, values);
return result;
}
}
}
它在倒数第二行失败了:
result = Activator.CreateInstance(specificType, values);
这很奇怪,因为它基本上与它之前执行的代码行完全相同:
result = Activator.CreateInstance(specificType, testArgs);
在这两种情况下,相同的参数被传递作为
specificType
参数,并且string[2]
作为第二个参数被传递。而
GimeStringTuples
方法可以正常工作...尽管那里没有涉及泛型,这可能是提示。有人能解释一下这种不寻常的行为吗?