本文介绍了如果值类型重载方法合并为一个通用的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在执行OO设计,是它更好地巩固使用简单的值类型为一个通用的方法,方法的集合?例如:

When performing OO design, is it better to consolidate a collection of methods that use simple value types into a generic method ? For example:

public int Sum(int x, int y)

// Overload with float.
public float Sum(float x, float y)



综合为:

Consolidated to:

public T Sum<T> (T x, T y)



谢谢,

Thanks,

斯科特

推荐答案

在总体不错,但是,特别是与你的榜样(求和两个参数) - 你不能做它与仿制药,因为 + 运营商没有任何接口,你可以限制你的泛型类型参数的一部分:)

In general yes, however, specifically with your example (summing two arguments) - you can't do it with generics, since the + operator is not part of any interface to which you can constrain your generic type argument :)

(注:这是我的C#的部分谈话,其他语言可能仍然是可能的)

(Note: this is my C# part talking, in other languages that might still be possible)

这篇关于如果值类型重载方法合并为一个通用的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:36