是否有一个通用的限制,我可以使用+操作? [英] Is there a generic constraint I could use for the + operator?

查看:105
本文介绍了是否有一个通用的限制,我可以使用+操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些',其中'类型约束上可以添加,使follwing code编译?

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(或以上),使用动态,它支持 + ,但没有提供编译时检查

  • 在.NET 3.5(或以上), MiscUtil 提供了一个操作员 这使得可以作为运营商的方法的 - 再次,没有任何编译时检查

  • 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天全站免登陆