将类泛型类型约束为元组

Mae*_*ato 6 .net c# generics c#-4.0

  1. 我想用一个通用TKey创建一个类,其中TKey是可以创建的System.Tuple类型之一.

    public class Class1<TKey> where TKey : System.Tuple
    { 
           /// Class Stuff Goes Here where TKey is one of the 8 tuple 
               types found in the link in (1)
    
    }
    
    Run Code Online (Sandbox Code Playgroud)

我不太确定如何实现这一点.目标是防止自己为每个元组类实现一个类.

Jer*_*all 18

你不能像其他人所说的那样,但你几乎可以做到.

所以所有Tuple<...>类都有这样的签名:

public class Tuple<T1, ...> : 
    IStructuralEquatable, 
    IStructuralComparable, 
    IComparable, 
    ITuple
Run Code Online (Sandbox Code Playgroud)

所有这些接口保存ITuple都是公共的(ITuple是内部接口),因此您可以尝试制作类似的东西:

public interface ITupleKey<TKey>
    where TKey : IStructuralEquatable, IStructuralComparable, IComparable
{
}
Run Code Online (Sandbox Code Playgroud)

"但是等等!",你说,"我怎么能确定没有别的东西在实现这些接口呢?"

好吧,你做不到.但就像我说的,这只是一个基本方式-幸运的是,IStructuralEquatableIStructuralComparable只(在框架级别,自然)在以下类型使用:

System.Array
System.Tuple<T1>
System.Tuple<T1,T2>
System.Tuple<T1,T2,T3>
System.Tuple<T1,T2,T3,T4>
System.Tuple<T1,T2,T3,T4,T5>
System.Tuple<T1,T2,T3,T4,T5,T6>
System.Tuple<T1,T2,T3,T4,T5,T6,T7>
System.Tuple<T1,T2,T3,T4,T5,T6,T7,TRest>
Run Code Online (Sandbox Code Playgroud)

所以它非常接近.将它与运行时检查相结合,TKey实际上是一些变体Tuple,您可能拥有所需的内容.

编辑:

一些基本用法:

public class Class1<TKey> 
    where TKey : IStructuralEquatable, IStructuralComparable, IComparable
{ 
}

// will compile
var classTup1 = new Class1<Tuple<int>>();
var classTup2 = new Class1<Tuple<int,int>>();
var classTup3 = new Class1<Tuple<int,int,int>>();
var classTup4 = new Class1<Tuple<int,int,int,int>>();
var classTup5 = new Class1<Tuple<int,int,int,int,int>>();

// won't compile
var badclassTup1 = new Class1<int>();
var badclassTup2 = new Class1<string>();
var badclassTup3 = new Class1<object>();
Run Code Online (Sandbox Code Playgroud)

而且,因为我显然已经疯了,让我们看看这里有什么可能:

public class Class1<TKey> 
    where TKey : IStructuralEquatable, IStructuralComparable, IComparable
{ 
    public Class1(TKey key)
    {
        Key = key;
        TupleRank = typeof(TKey).GetGenericArguments().Count();
        TupleSubtypes = typeof(TKey).GetGenericArguments();
        Console.WriteLine("Key type is a Tuple (I think) with {0} elements", TupleRank);
        TupleGetters = 
            Enumerable.Range(1, TupleRank)
                .Select(i => typeof(TKey).GetProperty(string.Concat("Item",i.ToString())))
                .Select(pi => pi.GetGetMethod())
                .Select(getter => Delegate.CreateDelegate(
                            typeof(Func<>).MakeGenericType(getter.ReturnType), 
                            this.Key, 
                            getter))
                .ToList();
    }

    public int TupleRank {get; private set;}
    public IEnumerable<Type> TupleSubtypes {get; private set;}
    public IList<Delegate> TupleGetters {get; private set;}
    public TKey Key {get; private set;}

    public object this[int rank]
    {
        get { return TupleGetters[rank].DynamicInvoke(null);}
    }
    public void DoSomethingUseful()
    {
        for(int i=0; i<TupleRank; i++)
        {
            Console.WriteLine("Key value for {0}:{1}", string.Concat("Item", i+1), this[i]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

试验台:

var classTup1 = new Class1<Tuple<int>>(Tuple.Create(1));
var classTup2 = new Class1<Tuple<int,int>>(Tuple.Create(1,2));
var classTup3 = new Class1<Tuple<int,int,int>>(Tuple.Create(1,2,3));
var classTup4 = new Class1<Tuple<int,int,int,int>>(Tuple.Create(1,2,3,4));
var classTup5 = new Class1<Tuple<int,int,int,int,int>>(Tuple.Create(1,2,3,4,5));

classTup1.DoSomethingUseful();
classTup2.DoSomethingUseful();
classTup3.DoSomethingUseful();
classTup4.DoSomethingUseful();
classTup5.DoSomethingUseful();
Run Code Online (Sandbox Code Playgroud)

输出:

Key type is a Tuple (I think) with 1 elements
Key type is a Tuple (I think) with 2 elements
Key type is a Tuple (I think) with 3 elements
Key type is a Tuple (I think) with 4 elements
Key type is a Tuple (I think) with 5 elements
Key value for Item1:1
Key value for Item1:1
Key value for Item2:2
Key value for Item1:1
Key value for Item2:2
Key value for Item3:3
Key value for Item1:1
Key value for Item2:2
Key value for Item3:3
Key value for Item4:4
Key value for Item1:1
Key value for Item2:2
Key value for Item3:3
Key value for Item4:4
Key value for Item5:5
Run Code Online (Sandbox Code Playgroud)


Yos*_*nal 5

我很惊讶没有人建议您基于ITuple接口限制您的类(或在我的情况下是一个方法)。为了说明您的示例:

public class Class1<T> where T : ITuple
Run Code Online (Sandbox Code Playgroud)

您需要引用System.Runtime.CompilerServices程序集。

我的特定用例是我想遍历一组未知形状的元组。我的解决方案是:

public static void ProcessTupleCollection<T>(this IEnumerable<T> collection) where T: ITuple
{
    var type = typeof(T);
    var fields = type.GetFields();
    foreach (var item in collection)
    {
        foreach (var field in fields)
        {
            field.GetValue(item);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道这是一个旧的,但我希望这可以帮助那些可能偶然发现它的人:)

  • 我很惊讶您使用反射来访问您的“ITuple”值而不是使用索引,因为“ITuple”具有 Length 属性以及“Int32[Int32]”索引属性...+1,但您应该添加该信息为了完整性。[更多信息](https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.ituple?view=netframework-4.8) (2认同)

Ste*_*rov -1

就像这样:

public class Class1<TKey,P,Q> where TKey : System.Tuple<P,Q>
{ 
       /// Class Stuff Goes Here where TKey is one of the 8 tuple 
           types found in the link in (1)

}
Run Code Online (Sandbox Code Playgroud)

将 Tuple 的通用参数添加到您的类中'

根据下面的评论,如果没有接口或反射,就无法将其组合到一个类中。如果有的话就不会有多个 Tuple 类

但是...您可以定义自己的基接口,该接口由多个 Class1 继承,然后使用该接口作为约束。听起来不太漂亮,但可以用