运算符“+”无法应用于T与T类型的操作数, dynamic还有default赋默认值

作者:自然
链接:https://www.zhihu.com/question/269696928/answer/744846963
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

这个是用泛型传递进来的参数去做“+”运算,但没有进行泛型约束导致的错误。也就是说没有限定传递参数的类型“T”具体是什么类型,
因为并不是所有的类型都能运算的。
泛型应用比较返回布尔类型比较常见,在泛型中进行四则运算意义不大,实在要用可以考虑运算符重载,或定义一个dynamic弱类型的变量再进行运算。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.WebRequestMethods;

namespace xiketang.com.GenericTeach
{
    1.运算符重载:
	class A
	{
		public int x;
		public static A operator +(A a, A b)
		{
			A Temp = new A();
			Temp.x = a.x + b.x;
			return Temp;
		}
		public override string ToString()
		{
			return this.x.ToString();
		}
	}
	class B<T> where T : A, new()
	{
		public void Add(T t1, T t2)
		{
			T t3 = (T)(t1 + t2);
			Console.WriteLine(t3);
		}
	}


  //2.
	interface IAlgorthim<T> where T : struct // 约束于值类型
	{
		T Add(T t1, T t2);
	}
	class Algorthim<T> : IAlgorthim<T> where T : struct
	{
		public T Add(T t1, T t2)
		{
			dynamic first = t1, second = t2;  //这里用dynamic类型对两个泛型参数进行赋值,能使两个泛型参数进行运算
			return first + second;
		}
	}
}

default用法:

posted on 2023-07-15 09:33  manber  阅读(260)  评论(0)    收藏  举报

导航