C#数字基类 [英] C# numeric base class

查看:97
本文介绍了C#数字基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个可以接受任何数字的C#方法.像这样:

I want to write a C# method that can accept any number. Something like:

public static T Sum(T a, T b) where T : number {  // (not real code)
    return a + b;
}

但是我没有看到C#中的数字"基类,就像我使用的大多数其他语言一样.数值类型为IComparable,IFormattable,IConvertible,IComparable和IEquatable,但似乎没有任何算术功能.除了对象之外,它们都是结构,没有明显的公共超类. (请原谅我,如果我在这里搞不清楚的话,因为我不太熟悉C#结构以及它们与类类似或与类不同的所有方式.)

But I don't see a "number" base class in C#, as exists in most other languages I've used. The numeric value types are IComparable, IFormattable, IConvertible, IComparable, and IEquatable, but nothing that seems to have any arithmetic capabilities. They're all structs, with no apparent common superclass, apart from object. (Forgive me if I'm screwing up the meaning here, since I'm not too familiar with C# structs and precisely all the ways they are like or unlike classes.)

我错过了什么吗,还是无法在C#中编写一个执行"a + b"的方法而没有明确声明"+"上下文中a和b是什么的原因?

Am I missing something, or is it not possible to write a method in C# that does "a + b" without declaring exactly what a and b are in the context of the "+"?

推荐答案

您将不得不使用重载. Math类有点像Math.Max这样的功能,它支持所有数字类型.

You will have to resort to using overloading. A little like the Math class is doing with function like Math.Max where it support all numeric types.

CD提出的链接也很有用.

The link proposed by CD is also resourceful.

这篇关于C#数字基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆