是否有我可以用于 + 运算符的通用约束? [英] Is there a generic constraint I could use for the + operator?

查看:22
本文介绍了是否有我可以用于 + 运算符的通用约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以添加一些where"类型的约束来编译以下代码?

is there some 'where' type contraints in can add to make the follwing code compile ?

public class Plus<T> : BinaryOperator<T> where T : ...
{
    public override T Evaluate(IContext<T> context)
    {
        return left.Evaluate(context) + right.Evaluate(context);
    }
}

谢谢:)

推荐答案

C# 中没有这样的设备.不过,有几个选项可用:

There are no such devices in C#. A few options are available, though:

  • 在 C# 4.0 和 .NET 4.0(或更高版本)中,使用 dynamic,它支持 + 但不提供编译时检查
  • 在 .NET 3.5(或更高版本)中,MiscUtil 提供了一个 运算符 class 使运算符可用作方法 -再次,没有任何编译时检查
  • in C# 4.0 and .NET 4.0 (or above), use dynamic, which supports + but offers no compile time checking
  • in .NET 3.5 (or above), MiscUtil offers an Operator class which makes operators available as methods - again, without any compile-time checking

所以要么:

return (dynamic)left.Evaluate(context) + (dynamic)right.Evaluate(context);

return Operator.Add(left.Evaluate(context), right.Evaluate(context));

这篇关于是否有我可以用于 + 运算符的通用约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆