为什么 C# 中没有与 Ada 泛型参数等效的参数?
请注意,我不是在谈论通用类型参数。
例如,在 Ada 中,我可以编写一个需要使用值而不是类型进行初始化的包。例如
generic
Size : Positive;
package Sudokus is
subtype Values is Positive range 1..Size*Size;
type Choice is private;
type Sudoku is private;
procedure Fill(S : out Sudoku);
procedure Init(S : out Sudoku);
procedure Solve(S : in out Sudoku);
procedure Print(S : Sudoku);
Unsolvable_Grid_Error : exception;
,这就是如何使用它:
package My_Sudoku is new Sudokus(3); -- 3 for 9x9 solver, 4 for 16x16 solver, etc.
我想没有等效的,但我发现它非常有用。 这次缺席有原因吗?
Please note that I am not talking about Generic Type parameters.
For example in Ada I can write a package that needs to be initialized using a value instead of a type. e.g.
generic
Size : Positive;
package Sudokus is
subtype Values is Positive range 1..Size*Size;
type Choice is private;
type Sudoku is private;
procedure Fill(S : out Sudoku);
procedure Init(S : out Sudoku);
procedure Solve(S : in out Sudoku);
procedure Print(S : Sudoku);
Unsolvable_Grid_Error : exception;
And this is how to use it :
package My_Sudoku is new Sudokus(3); -- 3 for 9x9 solver, 4 for 16x16 solver, etc.
I guess there is no equivalent but I find it quite useful.
Is there a reason for this absence ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“为什么 C# 没有功能 X”的一般答案围绕着这种功能的好处与成本。好处通常是显而易见的,但成本包括:
基本上,不应该问为什么某个特定功能不存在:它应该是与成本相比,该功能的好处是巨大的。功能必须在语言中赢得一席之地,并且语言设计者已经设定了相当高的标准。 (正如 Anders 过去所说,每个功能的得分都是 -100,并且必须逐步提高。)
The general answer to "why does C# not have feature X" revolves around the benefits of such a feature versus the costs. Benefits are usually obvious, but costs include:
Basically, it shouldn't be a case of asking why a particular feature isn't present: it should be a matter of arguing that the benefits of the feature are enormous compared with the costs. Features have to earn their place in the language, and the language designers have set the bar pretty high. (As Anders has put it in the past, every feature starts out with a score of -100, and has to work its way up.)
为什么不简单地将大小传递给构造函数并用它初始化数组呢?
我能看到的“通用参数”的唯一优点是如果你有一个固定大小的数组,它可以允许更快的访问,但无论如何 C# 不支持这一点(至少不作为非局部变量)。
我知道 C++ 支持这种模板,这种模板远远优于 C# 或 Java 中的模板。
Why don't you simply pass the size to the constructor and initialize the array with it?
The only advantage I could see with a "generic parameter" is if you had a fixed size array, which could allow for faster access, but that isn't supported in C# anyway (at least not as non-local variable).
I know this kind of templating is supported in C++, which templating is far superior to templating in C# or Java.