怎么样实现泛型的数值计算?

zzPandazz 2010-12-23 10:44:07
比如有public T Func<T>(T t)这么一个函数
如果在函数体做运算会出现
运算符“*”无法应用于“T”和“T”类型的操作数等编译错误
...全文
159 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
Kevin0105 2010-12-23
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 timzhufaith 的回复:]
public T Func<T>(T t)
{
switch(t.GetType().Name)
{
case "System.Int32":
case "System.Single":
}
}
[/Quote]

支持!


另外:where T : int。
should be where T:struct 表示T 必须是值类型的值

zzPandazz 2010-12-23
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 timzhufaith 的回复:]
引用 2 楼 publicsub 的回复:
这是因为object没有重载运算符,你可以把泛型限定成数值类型,例如where T : int。
int 可以被继承么。。sealed
[/Quote]
int貌似被Serializable了
zzPandazz 2010-12-23
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 timzhufaith 的回复:]
c#是不可以的。。。只能用switch case来逐个判断
c++倒是可以
[/Quote]
是的,我知道C++可以,但是我现在要泛化的代码是C#的
shichao102471077 2010-12-23
  • 打赏
  • 举报
回复
见识了。这个你用. 试试
TimZhuFaith 2010-12-23
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 publicsub 的回复:]
这是因为object没有重载运算符,你可以把泛型限定成数值类型,例如where T : int。
[/Quote]int 可以被继承么。。sealed
TimZhuFaith 2010-12-23
  • 打赏
  • 举报
回复
public T Func<T>(T t)
{
switch(t.GetType().Name)
{
case "System.Int32":
case "System.Single":
}
}
publicsub 2010-12-23
  • 打赏
  • 举报
回复
这是因为object没有重载运算符,你可以把泛型限定成数值类型,例如where T : int。
TimZhuFaith 2010-12-23
  • 打赏
  • 举报
回复
c#是不可以的。。。只能用switch case来逐个判断
c++倒是可以
TimZhuFaith 2010-12-23
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 macooidle 的回复:]
C# code

using System;
using System.Reflection;
using System.Reflection.Emit;

namespace winfromTest
{
public class Test
{
private delegate TReturn TwoParameter<TReturn, TPar……
[/Quote]强大
macooidle 2010-12-23
  • 打赏
  • 举报
回复

using System;
using System.Reflection;
using System.Reflection.Emit;

namespace winfromTest
{
public class Test
{
private delegate TReturn TwoParameter<TReturn, TParameter0, TParameter1>
(TParameter0 p0, TParameter1 p1);

public T Mul<T>(T t1, T t2)
{
Type[] methodArgs = { typeof(T), typeof(T) };

DynamicMethod multiplyHidden = new DynamicMethod(
"",
typeof(T),
methodArgs,
typeof(Test).Module);

ILGenerator il = multiplyHidden.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Ret);


TwoParameter<T, T, T> invoke = (TwoParameter<T, T, T>)
multiplyHidden.CreateDelegate(
typeof(TwoParameter<T, T, T>)
);

return invoke(t1, t2);
}
}
}

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧