C# 中的别名技术?
假设我想使用假设的语法在 C# 中创建类型的别名:
Currency = float;
然后我离开并创建数千个使用 Currency
类型的文件。
然后我意识到我更喜欢使用 FCL 类型:
Currency = System.Single;
太好了,所有代码仍然有效。
...几个月后...
等等,我遇到了一些奇怪的舍入错误。哦,这就是为什么 System.Single
只有 7 位数字精度。让其达到 15 位:
Currency = System.Double;
...几年后...
哦哦,浮点数并不精确;乘以 $0.0011/unit * 217,384units
会暴露出使用浮点的一些限制。会计师坚决反对“会计违规行为”。没问题:
Currency = System.Decimal;
...几年后...
国际申请?货币代码。嗯嗯。 谢谢 CodeProject:
Currency = Money;
...稍后...
噢,模式和实践。让我们混淆一些代码:
Currency = ICurrency;
在所有这些无意义的代码中并没有破坏。
我知道 C# 不支持这种级别的封装和我编写的语法的弹性。
Assume i want to create an alias of a type in C# using a hypothetical syntax:
Currency = float;
Then i go away and create a few thousand files that use Currency
type.
Then i realize that i prefer to use FCL types:
Currency = System.Single;
Excellent, all code still works.
...months later...
Wait, i'm getting some strange rounding errors. Oh that's why, System.Single
only has 7 digits of precision. Lets up that to 15 digits:
Currency = System.Double;
...years later...
Ohhhh, floating point isn't exact; multiplying $0.0011/unit * 217,384 units
exposes some limitations of using floating point. And accountants are sticklers against "accounting irregularities". No problem:
Currency = System.Decimal;
...years later...
International applications? Currency codes. Hmmmm. Thank you CodeProject:
Currency = Money;
...later...
Ooo, patterns and practices. Let's obfuscate some of that code:
Currency = ICurrency;
And during all this nonsense code didn't break.
i know C# doesn't support this level of encapsulation and resilency with the syntax i made up.
But can anyone suggest a syntax that can simulate what people have been trying to accomplish (including myself)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建一个名为Currency 的类并实现(或委托)适当的运算符,然后只需在需要时更改用于在内部存储数据的类即可。
Create a class called Currency and implement (or delegate) the appropriate operators, then just change the class used to store the data internally when desired.
您可以像这样使用
using
:usingCurrency = System.Single;
,但您必须在每个文件中执行此操作。但与在整个应用程序中搜索单个相比,更改仍然更容易。You can use
using
like so:using Currency = System.Single;
, but you must do it in every single file. But still easier to change, than searching for single in whole application.