C# 如何为所有积分类型建立一个扩展方法?

C# 如何为所有积分类型建立一个扩展方法?,c#,C#,我已经编写了一个作用于int的静态扩展方法,但是我想让它更健壮地作用于任何对象,例如ushort或char。除了代码重复之外,有什么方法可以做到这一点吗 现在,我的方法签名如下所示: public static class ExtensionMethods { public static T MyCoolMethod<T>(this int value) where T : struct, IConvertible { ... } } 公共静

我已经编写了一个作用于
int
的静态扩展方法,但是我想让它更健壮地作用于任何对象,例如
ushort
char
。除了代码重复之外,有什么方法可以做到这一点吗

现在,我的方法签名如下所示:

public static class ExtensionMethods
{
    public static T MyCoolMethod<T>(this int value) where T : struct, IConvertible
    {
        ...
    }
}
公共静态类扩展方法
{
公共静态T myColMethod(此int值),其中T:struct,IConvertible
{
...
}
}

我是否可以将
int
替换为一些公共接口,或者使用泛型执行其他操作以获得它,以便此扩展方法可以应用于任何整数类型?

不,您不能。您应该编写一些基本方法,并从基于特定类型的每个实现中调用它。

不,您不能在编译时这样做;这是因为整数类型没有通用约束。然而,在运行时,您可以检查是否存在和抛出以及错误


如果你的方法对<代码>结构> <代码>进行约束,你应该考虑把它放在那个位置。

,尝试搜索。我准备把它作为答案,但是它关闭了。尝试将您的方法签名修改为
公共静态T myColMethod(此T值),其中T:struct,IConvertible
,但您不能约束为整数类型,它将出现在同时是struct和IConvertible的任何类型上。@SoaperGEM,@Ron:您可能可以将其固定得稍微紧一点:类似于
其中T:struct,IComparable、IConvertible、IFormattable、IComparable、IEquatable
,尽管它还远远不够完美。@SoaperGEM这也很简单
publicstatictmycolmethod(这个U值),其中U…
您可以有多个泛型。不,您只需重复“where”部分,比如
Method(这个U值),其中T:struct,IConvertible,其中U:struct,IConvertible,IFormattable,