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

标签 c# dictionary tuples

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

所以如果我想要一个大小为 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/

相关文章:

python - 如何修改元组列表中包含给定索引的特定值的元组

ios - 如何在不使用库swift的情况下反序列化json响应类型

c# - 我如何伪造 Assembly.LoadFile 和 Assembly.GetTypes?

c# - JQUERY 按钮返回索引元素

c# - 如何轮询目录中的文件

c# - 向字符串类 C# 添加新属性

python - 如何将从用户获取的多个值分配给存储在Python字典中的单个键?

python - 将列表 Dict 转换为 DataFrame : Pandas

python - Flask 中的 JSON 数据是字符串还是字典?

python - 如何连接元组