我希望动态创建具有相同类型的给定大小的元组。
所以如果我想要一个大小为 3 的字符串元组,我会得到 Tuple
我都试过像这样将字符串传递到 Tuple 的尖括号中:
string foo = "string, string, string";
Tuple<foo> testTuple = Tuple<foo>(~parameters~);
并将类型数组传递到尖括号中,如下所示:
List<Type> types = new List<Type>() {"".GetType(), "".GetType(), "".GetType()};
Tuple<types> testTuple = Tuple<foo>(~parameters~);
这些都没有用。有谁知道如何制作所描述的动态元组?
(我想这样做的原因是在像
这样的字典中使用元组Dictionary<Tuple<# strings>, int> testDictionary = new Dictionary<Tuple<x # strings>, int>();
在这里使用元组比 HashSet 更有用,因为元组中的比较是通过组件而不是通过引用进行的,所以如果我有
Tuple<string, string> testTuple1 = new Tuple<string, string>("yes", "no");
Tuple<string, string> testTuple2 = new Tuple<string, string>("yes", "no");
Dictionary<Tuple<string, string>, string> testDictionary = new Dictionary<Tuple<string, string>, string>() {
{testTuple1, "maybe"}
};
Console.WriteLine(testDict[testTuple2]);
它写着“也许”。如果您使用 HashSet 运行相同的测试,它会抛出一个错误。如果有更好的方法来完成同样的事情,那也会很有用。)
最佳答案
你可以使用反射做这样的事情:
public static object GetTuple<T>(params T[] values)
{
Type genericType = Type.GetType("System.Tuple`" + values.Length);
Type[] typeArgs = values.Select(_ => typeof(T)).ToArray();
Type specificType = genericType.MakeGenericType(typeArgs);
object[] constructorArguments = values.Cast<object>().ToArray();
return Activator.CreateInstance(specificType, constructorArguments);
}
这将为您提供一个包含可变数量元素的元组。
关于c# - 动态创建一个具有所有相同类型和已知数量元素的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43126224/