Skip to main content
 首页 » 编程设计

c#之我可以扩展一个泛型类来限制可以使用的类型吗

2024年02月23日16zhengyun_ustc

我想扩展 IEnumerable 类,但仅限于可以操作的类型(int、decimal、single 和 double)。

这可行吗?我看不到限制这个的方法:

public static class IEnumerableExtension 
{ 
    public static decimal FindBestSubsequence<T> (this IEnumerable<T> source, out int startIndex, out int endIndex) 
    { 
 
    } 
} 

提前致谢。

请您参考如下方法:

您正在寻找 generic constraints但是您不能将类型参数限制为仅对一组特定类型有效。你能想到的最接近的是这样的:

public static decimal FindBestSubsequence<T> 
    (this IEnumerable<T> source, out int startIndex, out int endIndex)     
     where T : struct, IConvertible, IFormattable, IComparable<T>, IEquatable<T>, 
     IComparable 

...因为这些都是这些类型中的每一个实现的所有接口(interface)。但是,这不会阻止,比如说,Int16。从被用作类型参数。你绝对不希望它适用于IEnumerable<short>吗? ?如果用于此,会出现什么问题?

您可以有一组非泛型公共(public)重载,然后调用受约束的泛型私有(private)方法:

public static decimal FindBestSubsequence(this IEnumerable<decimal> source, 
    out int startIndex, out int endIndex) 
{ 
    return FindBestSubsequenceImpl(source, startIndex, endIndex); 
} 
 
public static decimal FindBestSubsequence(this IEnumerable<int> source, 
    out int startIndex, out int endIndex) 
{ 
    return FindBestSubsequenceImpl(source, startIndex, endIndex); 
} 
 
// etc 
 
// Could constrain T more if it was useful in the method, but we know 
// T will only be one of the types we want, because only this class can 
// call this method 
private static decimal FindBestSubsequence<T> 
    (IEnumerable<T> source, out int startIndex, out int endIndex)     
     where T : struct 
{ 
}