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

╄→гoц情女王★ 提交于 2019-11-27 01:57:33
Marc Gravell

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

So either:

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

or

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

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 +

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.

do you mean a generic constraint?

http://msdn.microsoft.com/en-us/library/d5x73970.aspx

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