相关疑难解决方法(0)

定义实现+运算符的泛型

可能重复:
.NET泛型中重载运算符约束的解决方案

我有一个问题我正在努力,目前它正在为ints 工作,但我希望它适用于所有可以使用+运算符添加的类.有没有办法在通用中定义它?例如,

public List<T> Foo<T>() where T : ISummable
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

编辑:
传递代理进行求和而不是使用+ =类型的Int的性能最好慢540%.调查可能的其他解决方案

最终解决方案:
谢谢大家的建议.我最终找到了一个不太慢的解决方案,并在编译时强制执行检查.当一位同事帮我解决这个问题时,我无法完全信任.无论如何,这里是:

以函数的形式实现一个包含所有必需操作符的接口

public interface IFoo<InputType, OutputType>
{
    //Adds A to B and returns a value of type OutputType
    OutputType Add(InputType a, InputType b);
    //Subtracts A from B and returns a value of type OutputType
    OutputType Subtract(InputType a, InputType b);
}
Run Code Online (Sandbox Code Playgroud)

创建要定义的类,但不使用Where子句,而是使用IFoo接口的依赖注入实例.OutputType通常是双倍的,因为操作的性质是数学的.

public class Bar<T>
{
    private readonly IFoo<T,double> _operators;

    public Bar(IFoo<T, double> operators)
    {
        _operators = operators;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当您使用此类时,您可以像这样定义操作规则: …

c# generics operators

8
推荐指数
1
解决办法
2008
查看次数

标签 统计

c# ×1

generics ×1

operators ×1