.Net 和 C# 中的多态数字 [英] Polymorphic Numerics on .Net and In C#

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

问题描述

.Net 中没有数字的多态性,即没有统一不同类型的数字类型(如 bool、byte、uint、int 等)的 INumeric 接口,这真是令人遗憾.在极端情况下,人们想要一个完整的抽象代数类型包.

It's a real shame that in .Net there is no polymorphism for numbers, i.e. no INumeric interface that unifies the different kinds of numerical types such as bool, byte, uint, int, etc. In the extreme one would like a complete package of abstract algebra types.

Joe Duffy 有一篇关于这个问题的文章:

Joe Duffy has an article about the issue:

http://www.bluebytesoftware.com/blog/CommentView,guid,14b37ade-3110-4596-9d6e-bacdcd75baa8.aspx

您将如何在 C# 中表达这一点,以便对其进行改造,而不影响 .Net 或 C#?

How would you express this in C#, in order to retrofit it, without having influence over .Net or C#?

我有一个想法,首先定义一个或多个抽象类型(接口,如 Inumeric - 或更抽象),然后定义实现这些的结构并包装类型,如 int,同时提供返回新类型的操作(例如 Integer32 : Inumeric; 其中加法定义为

I have one idea that involves first defining one or more abstract types (interfaces such as INumeric - or more abstract than that) and then defining structs that implement these and wrap types such as int while providing operations that return the new type (e.g. Integer32 : INumeric; where addition would be defined as

public Integer32 Add(Integer32 other)
{
    return Return(Value + other.Value);
}

我有点害怕这段代码的执行速度,但至少它是抽象的.

I am somewhat afraid of the execution speed of this code but at least it is abstract.

没有运算符重载的好处...

No operator overloading goodness...

还有其他想法吗?

.Net 看起来不像是一个可行的长期平台,如果它不能拥有我认为的这种抽象 - 并且对其进行高效处理.

.Net doesn't look like a viable long-term platform if it cannot have this kind of abstraction I think - and be efficient about it.

抽象就是重用.

更新:

这是迄今为止的示例实现类型签名:

This is an example implementation type signature so far:

public struct Integer32 : INumeric<Integer32, Int32>, IOrder<Integer32, Int32>

补偿缺乏协变返回类型.

Compensating for the lack of covariant return types.

推荐答案

有人已经开始努力编写一些可以解决您的困境的东西.它称为 泛型运算符,可在 杂项实用程序库.

Someone has already gone to the effort of writing something which may solve your delemma. It's called Generic Operators, and is available in the Miscellaneous Utility Library.

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

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