本文介绍了比较特殊的仿制药?在C#泛型算术可能的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,在C#泛型不允许进行算术任何理智的方式。有可用的尴尬解决办法,但他们都不是很整齐,他们都降低性能。
根据,用算术类型的接口是不可能实现,所以这样的一个解决方法建议。



Why should I have to tell an advanced programming language how to add and multiply numbers?[Edited due to popular demand]

Why not simply allow a Generic to be restricted to a list of types?

Eg.

class Matrix<T> where T : int,long,float,double

The syntax could of course be different. But the compiler needs only to check that the type is on the list, and that the operators used work on all types, which should be much simpler than the apparently-too-difficult interface suggestion.

Are there any obvious reasons as to why this cannot be implemented?

解决方案

I think you are looking for the functionality of a functional programming language in OOP. If that is the case, then use FP.

For example, in Scala, you can replace the operators, so now it can add or multiply your matrix.

This is the case in various languages, but not all OOP languages.

Why should generics be able to do addition when it isn't obvious how to add or multiply? For example, if I have a class of logarithms, then to multiply is just adding the numbers, but, how could a compiler know that?

In C# you can do operator overloading, which should solve the problem you are complaining about:http://msdn.microsoft.com/en-us/library/aa288467%28VS.71%29.aspx

The C# team came to decisions on how to do generics, and it shouldn't handle math as my example above would show, but they did allow for you to help the compiler know how to do the math operations, so blaming them for not asking them for your opinion first is very risky, as the decision has been made, generics are in as they are. It won't be changed now, I believe.

这篇关于比较特殊的仿制药?在C#泛型算术可能的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 19:02