【问题标题】:Dynamically create a tuple with all the same type and a known number of elements动态创建一个具有所有相同类型和已知数量元素的元组
【发布时间】:2017-08-24 20:55:50
【问题描述】:

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

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

在这里使用元组比 HashSets 更有用,因为元组中的比较是通过组件而不是通过引用,所以如果我有

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]);

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

【问题讨论】:

  • 您似乎有一些外部需求,您正试图将它们塞进框架类型(元组、字典)中。别。创建自定义类型,以您需要的方式保存您需要的数据。

标签: c# dictionary tuples


【解决方案1】:

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

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

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

【讨论】:

  • 您可以将其转换为元组而不是对象,以至少在编译时返回 Tuple&lt;,,&gt; 类型:return (Tuple&lt;object, object, object&gt;)Activator.CreateInstance(specificType, values); 并返回 Tuple&lt;object, object, object&gt; 而不是 object
  • @Quantic 假设您知道您将采用多少参数参数......我假设我们不知道。
  • 啊,我明白了,我不知何故错过了项目数量本身是动态的这一事实,而您使用字符串 "System.Tuple`" + values.Length 解决了这个问题。
【解决方案2】:

“有人知道如何制作所描述的动态元组吗?”

您可以使用Tuple.Create()。对于3-tuple

var tupleOfStrings = Tuple.Create("string1", "string2", "string3");
var tupleOfInts = Tuple.Create(1, 2, 3);

【讨论】:

    【解决方案3】:

    在内部使用List&lt;string&gt; 制作自定义类型(如果您想要通用解决方案,则使用List&lt;T&gt;

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2014-01-03
      • 2016-04-26
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      相关资源
      最近更新 更多