问题
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 has an article about the issue:
http://www.bluebytesoftware.com/blog/CommentView,guid,14b37ade-3110-4596-9d6e-bacdcd75baa8.aspx
How would you express this in C#, in order to retrofit it, without having influence over .Net or C#?
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...
Any other ideas?
.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.
Abstraction is reuse.
update:
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.
回答1:
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.
回答2:
The csharp language team is already looking into this. If you want a view onto the future of type classes in C# start reading at
https://github.com/dotnet/csharplang/issues/164
It seems to have the support of Mads Torgesson so it's not just a random post by a wandering Haskell fanboy.
The example given of a typeclass or shape in C# land is
public shape SGroup<T>
{
static T operator +(T t1, T t2);
static T Zero { get; }
}
notice this is not like an interface. It is declaring static method that belong to SGroup. Read on for more details and discussion.
回答3:
If you plan to use C# 4.0 then you can easily simulate generic mathematical operations using dynamic
. Here is an example of a simple addition function (for more information see this blog):
public static T Add<T>(T a, T b) {
dynamic ad = a;
dynamic bd = b;
return ad + bd;
}
I haven't played with this, so I can't say much about the performance. There will certainly be some performance price for using dynamic, but I think the DLR should be able to do very effective optimizations if you'll invoke the function multiple times. In fact, I won't be surprised if it had similar performance profile as Generic Operators mentioned above.
来源:https://stackoverflow.com/questions/2404731/polymorphic-numerics-on-net-and-in-c-sharp