Is there a generic constraint I could use for the + operator?

安稳与你 提交于 2019-11-26 09:54:13

问题


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);
    }
}

Thanks :)


回答1:


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

  • 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

So either:

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

or

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



回答2:


The Type parameter constraints in C# are very limited and is listed here. So the answer is no as far as compile time check goes. If T is a type that you create and manage, one way to go about it would be to

interface IAddable 
{
   IAddable Add(IAddable foo);
}

and implement IFoo for all your types and use where T: IAddable as constraint and use Add() instead of +




回答3:


Using a generic constraints you can force T

  • to be a reference type or a value type
  • to inherit from a certain class
  • to implement certain interface
  • to have parameterless constructor

But that's all. You can't force the existence of the static operator+ on it.



来源:https://stackoverflow.com/questions/5997107/is-there-a-generic-constraint-i-could-use-for-the-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!