如何动态创建.NET C#ValueType元组?

时间:2019-03-19 09:55:34

标签: c# .net .net-core dynamically-generated valuetuple

我想根据一个值集合动态创建一个值类型元组。

示例:我有一个给定的IEnumerable<T>,我想基于该集合创建一个元组。

我该如何实现?

It seems that the access within a value type tuple can be achieved dynamically,但没有任何指示可用于创建值类型元组的相同操作。

我的目的之一是利用此类article

中描述的元组的Equality和HashCode属性

3 个答案:

答案 0 :(得分:4)

问题仍然不清楚,但是我想您想将a集合转换为(a[0], a[1], a[2], …)形式的值元组。任何内置功能均不支持此功能。此外,由于.NET Framework仅定义多达ValueTuple<T1, …, T7>的内容,您很快就会遇到限制–超出此范围,您将需要使用ValueTuple<T1, …, T7, TRest>(例如ValueTuple<T1, …, T7, ValueTuple<T1, …, T7, ValueTuple<T1, …>>>)构造笨拙的嵌套值元组。

如果要实现集合相等性比较,则应改用IEqualityComparer<ICollection<T>>。这是来自SequenceEqualityComparer的示例实现:

public class SequenceEqualityComparer<TElement> : EqualityComparer<IEnumerable<TElement>>
{
    private readonly IEqualityComparer<TElement> _elementEqualityComparer;

    public SequenceEqualityComparer()
        : this(null)
    { }

    public SequenceEqualityComparer(IEqualityComparer<TElement> elementEqualityComparer)
    {
        _elementEqualityComparer = elementEqualityComparer ?? EqualityComparer<TElement>.Default;
    }

    public new static SequenceEqualityComparer<TElement> Default { get; } = new SequenceEqualityComparer<TElement>();

    public override bool Equals(IEnumerable<TElement> x, IEnumerable<TElement> y)
    {
        if (object.ReferenceEquals(x, y))
            return true;
        if (x == null || y == null)
            return false;

        if (x is ICollection<TElement> xCollection &&
            y is ICollection<TElement> yCollection &&
            xCollection.Count != yCollection.Count)
            return false;

        return x.SequenceEqual(y, _elementEqualityComparer);
    }

    public override int GetHashCode(IEnumerable<TElement> sequence)
    {
        if (sequence == null)
            return 0;

        unchecked
        {
            const uint fnvPrime = 16777619;
            uint hash = 2166136261;

            foreach (uint item in sequence.Select(_elementEqualityComparer.GetHashCode))
                hash = (hash ^ item) * fnvPrime;

            return (int)hash;
        }
    }
}

编辑:有趣的是,这是我对您实际问题的实现,使用反射和递归:

public static object CreateValueTuple<T>(ICollection<T> collection)
{
    object[] items;
    Type[] parameterTypes;

    if (collection.Count <= 7)
    {
        items = collection.Cast<object>().ToArray();
        parameterTypes = Enumerable.Repeat(typeof(T), collection.Count).ToArray();
    }
    else
    {
        var rest = CreateValueTuple(collection.Skip(7).ToArray());
        items = collection.Take(7).Cast<object>().Append(rest).ToArray();
        parameterTypes = Enumerable.Repeat(typeof(T), 7).Append(rest.GetType()).ToArray();
    }

    var createMethod = typeof(ValueTuple).GetMethods()
        .Where(m => m.Name == "Create" && m.GetParameters().Length == items.Length)
        .SingleOrDefault() ?? throw new NotSupportedException("ValueTuple.Create method not found.");

    var createGenericMethod = createMethod.MakeGenericMethod(parameterTypes);

    var valueTuple = createGenericMethod.Invoke(null, items);
    return valueTuple;
}

样品使用:

var collection = new[] { 5, 6, 6, 2, 8, 4, 6, 2, 6, 8, 3, 6, 3, 7, 4, 1, 6 };
var valueTuple = CreateValueTuple(collection);
// result: (5, 6, 6, 2, 8, 4, 6, (2, 6, 8, 3, 6, 3, 7, (4, 1, 6)))

如果您不介意Item8被装箱,则可以省去反射:

public static object CreateValueTuple<T>(IList<T> list)
{
    switch (list.Count)
    {
        case 0: return default(ValueTuple);
        case 1: return (list[0]);
        case 2: return (list[0], list[1]);
        case 3: return (list[0], list[1], list[2]);
        case 4: return (list[0], list[1], list[2], list[3]);
        case 5: return (list[0], list[1], list[2], list[3], list[4]);
        case 6: return (list[0], list[1], list[2], list[3], list[4], list[5]);
        case 7: return (list[0], list[1], list[2], list[3], list[4], list[5], list[6]);
        default: return (list[0], list[1], list[2], list[3], list[4], list[5], list[6], CreateValueTuple(list.Skip(7).ToList()));
    }
}

区别在于基于反射的方法会生成以下类型的结果:

ValueTuple<int,int,int,int,int,int,int,ValueTuple<ValueTuple<int,int,int,int,int,int,int,ValueTuple<ValueTuple<int,int,int>>>>>

…虽然基于开关的方法会生成:

ValueTuple<int,int,int,int,int,int,int,ValueTuple<object>>

在每种情况下,都有一个冗余的单个组件ValueTuple<T>包装嵌套的值元组。这是.NET Framework中ValueTuple.Create<T1, …, T8>方法实现的不幸设计缺陷,甚至在使用值元组语法(例如(1, 2, 3, 4, 5, 6, 7, (8, 9)))时也会发生。

public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8)
{
    return new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>(item1, item2, item3, item4, item5, item6, item7, ValueTuple.Create(item8));
}

如canton7所述,您可以通过直接使用ValueTuple<T1, …, T7, TRest>()构造函数来解决它,如their answer所示。

答案 1 :(得分:1)

要回答实际问题,请有兴趣的人...

正如其他人所说,如果只想确定两个序列是否相等,或者获取两个序列的哈希码,请不要执行此操作。有更好,更便宜的方法。

涉及到一点。 BCL定义ValueTuple<T>ValueTuple<T1, T2>等,最多ValueTuple<T1, T2, T3, T4, T5, T6, T7>。之后,您需要使用ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>,其中TRest本身就是某种ValueTuple(可以这样链接)。

public static class Program
{
    private const int maxTupleMembers = 7;
    private const int maxTupleArity = maxTupleMembers + 1;
    private static readonly Type[] tupleTypes = new[]
    {
        typeof(ValueTuple<>),
        typeof(ValueTuple<,>),
        typeof(ValueTuple<,,>),
        typeof(ValueTuple<,,,>),
        typeof(ValueTuple<,,,,>),
        typeof(ValueTuple<,,,,,>),
        typeof(ValueTuple<,,,,,,>),
        typeof(ValueTuple<,,,,,,,>),
    };

    public static void Main()
    {
        var a = CreateTuple(new[] { 1 });
        var b = CreateTuple(new[] { 1, 2, 3, 4, 5, 6, 7 });
        var c = CreateTuple(new[] { 1, 2, 3, 4, 5, 6, 7, 8 });
        var d = CreateTuple(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 });
        var e = CreateTuple(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 });
    }

    private static object CreateTuple<T>(IReadOnlyList<T> values)
    {
        int numTuples = (int)Math.Ceiling((double)values.Count / maxTupleMembers);

        object currentTuple = null;
        Type currentTupleType = null;

        // We need to work backwards, from the last tuple
        for (int tupleIndex = numTuples - 1; tupleIndex >= 0; tupleIndex--)
        {
            bool hasRest = currentTuple != null;
            int numTupleMembers = hasRest ? maxTupleMembers : values.Count - (maxTupleMembers * tupleIndex);
            int tupleArity = numTupleMembers + (hasRest ? 1 : 0);

            var typeArguments = new Type[tupleArity];
            object[] ctorParameters = new object[tupleArity];
            for (int i = 0; i < numTupleMembers; i++)
            {
                typeArguments[i] = typeof(T);
                ctorParameters[i] = values[tupleIndex * maxTupleMembers + i];
            }
            if (hasRest)
            {
                typeArguments[typeArguments.Length - 1] = currentTupleType;
                ctorParameters[ctorParameters.Length - 1] = currentTuple;
            }

            currentTupleType = tupleTypes[tupleArity - 1].MakeGenericType(typeArguments);
            currentTuple = currentTupleType.GetConstructors()[0].Invoke(ctorParameters);
        }

        return currentTuple;
    }
}

答案 2 :(得分:0)

仅供参考,我这样做是在EntityFrameworkCore模拟库here中生成一个密钥。

但是正如道格拉斯所指出的那样,ValueTuple定义仅限于7个参数,但是对于模拟库的用例来说,这很好。

无论如何,从本质上讲,代码将如下所示:

var valueTupleType = Type.GetType($"System.ValueTuple`{collection.Length}")
    ?? throw new InvalidOperationException($"No ValueTuple type found for {collection.Length} generic arguments");

var itemTypes = collection.Select(x => x.GetType()).ToArray();
var constructor = valueTupleType.MakeGenericType(itemTypes).GetConstructor(itemTypes)
    ?? throw new InvalidOperationException("No ValueTuple constructor found for key values");

var valueTuple = constructor.Invoke(collection);