How to conditionally invoke a generic method with constraints? [duplicate]

让人想犯罪 __ 提交于 2021-02-17 08:27:34

问题


Suppose I have an unconstrained generic method that works on all types supporting equality. It performs pairwise equality checks and so works in O(n2):

public static int CountDuplicates<T>(IList<T> list) 
{
    /* ... */ 
}

I also have a constrained generic method that only works with types supporting sorting. It starts from sorting the list in O(n log n), and then counts all duplicates in one pass:

public static int CountDuplicatesFast<T>(IList<T> list) 
    where T : IComparable<T> 
{
    /* ... */ 
}

So, a caller can choose to invoke the fast method if it is statically known that the type of elements of the list supports ordering. It might happen that the caller itself works with generic IList<T> where T is unconstrained, so its only option to invoke the first (slow) method.

Now, I want the first method to check at runtime if the type T actually implements the interface IComparable<T> and if so, invoke the fast method:

public static int CountDuplicates<T>(IList<T> list)
{
    if (typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
    {
        return CountDuplicatesFast(list);
    }
    else
    {
        /* use the slow algorithm */
    }
}

The problem is the compiler rejects the invocation CountDuplicatesFast(list):

error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Program.CountDuplicatesFast<T>(System.Collections.Generic.IList<T>)'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable<T>'.

Is it possible to persuade the compiler to trust me that I know what I am doing, and to skip the constraint check?


回答1:


Here's a way to do it using dynamic:

if (typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
{
    return CountDuplicatesFast((dynamic)list);
}

Or with reflection:

if (typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
{
    var method = typeof(MyType).GetMethod("CountDuplicatesFast");
    var generic = method.MakeGenericMethod(typeof(T));
    return (int)generic.Invoke(null, new object[] { list });
}

I don't think that there's a way to do this statically (i.e. without reflection or dynamic).




回答2:


You can use a helper class and dynamic type to skip compile-time checks:

sealed class CountDuplicatesFastCaller
{
    public int Call<T>(IList<T> list) where T : IComparable<T>
    {
        return CountDuplicatesFast(list);
    }
}

public static int CountDuplicates<T>(IList<T> list)
{
    if (typeof (IComparable<T>).IsAssignableFrom(typeof (T)))
    {
        return ((dynamic) new CountDuplicatesFastCaller()).Call(list);
    }
    else
    {
        /* use the slow algorithm */
    }
}

This should be faster than pure reflection because of DLR caching mechanisms.



来源:https://stackoverflow.com/questions/16405698/how-to-conditionally-invoke-a-generic-method-with-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!