动态创建一个具有所有相同类型和已知数量元素的元组

Sar*_*lyn 5 c# dictionary tuples

我希望动态创建具有相同类型的给定大小的元组。

因此,如果我想要一个大小为 3 的字符串元组,我会得到 Tuple<string, string, string>

我已经尝试将字符串传递到元组的尖括号中,如下所示:

string foo = "string, string, string";
Tuple<foo> testTuple = Tuple<foo>(~parameters~);
Run Code Online (Sandbox Code Playgroud)

并将类型数组传递到尖括号中,如下所示:

List<Type> types = new List<Type>() {"".GetType(), "".GetType(), "".GetType()};
Tuple<types> testTuple = Tuple<foo>(~parameters~);
Run Code Online (Sandbox Code Playgroud)

这些都不起作用。有谁知道如何制作所描述的动态元组?

(我想这样做的原因是在字典中使用元组,例如

Dictionary<Tuple<# strings>, int> testDictionary = new Dictionary<Tuple<x # strings>, int>();
Run Code Online (Sandbox Code Playgroud)

在这里使用元组比 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]);
Run Code Online (Sandbox Code Playgroud)

它写着“也许”。如果您使用 HashSets 运行相同的测试,则会抛出错误。如果有更好的方法来完成同样的事情,那也会很有用。)

Jam*_*ell 5

你可以使用反射来做这样的事情:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

这将为您提供一个包含可变数量元素的元组。


Den*_*kov 0

使用List<string>内部创建自定义类型(或者List<T>如果您想要通用解决方案)

覆盖object.Equals:用于Enumerable.SequenceEqual自定义类中的内部列表

覆盖object.GetHashCode()以使用您在字典中的类型