转换类可扩展性(扩展方法与 Parital 类)

发布于 2024-07-27 18:57:24 字数 402 浏览 11 评论 0原文

我正在创建一个频率转换类,我希望我的团队能够在需要时添加其他转换。

Frequency myFrequency = new Frequency(100, MHz);
double value = myFrequency.InKhz();

该类的源代码不会包含在未来的项目中,因此我要么必须让该类成为部分类,要么需要将额外的转换作为扩展。 一个例子是添加到 GHz 的转换

myFrequency.InGHz()

哪种是继续此操作的最佳方法?

更新:阅读 Randolpho 的答案后,我将采用扩展方法。 随着时间的推移,扩展将被纳入基本代码中,但我不想让其他团队成员等待更新的程序集,这使他们可以更快地继续执行下一个任务。

I am creating a conversion class for frequency, and I wanted to allow my team to be able to add additional conversions when they are needed.

Frequency myFrequency = new Frequency(100, MHz);
double value = myFrequency.InKhz();

The source code for the class will not be include in future projects, so I will either have to have the class be a partial class or the additional conversions will need to be extensions. An example would be adding a conversion to GHz

myFrequency.InGHz()

Which is the best way to proceed with this?

Update: After reading Randolpho's answer I am going with the extension method approach. As time allows the extensions will get rolled into the base code, but I didn't want to make the other team members wait for updated assemblies and this allows them to move on to the next task a little faster.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你怎么敢 2024-08-03 18:57:24

除非您有原始来源,否则部分类将无法工作。 如果您拒绝开发人员访问该源,他们唯一的选择就是使用扩展方法。

也就是说,您可能只想有一个过程来更新库以添加新内容; 看起来它们会很罕见。

Partial classes will not work unless you have the original source. If you are denying the developers access to that source, their only alternative is to use extension methods.

That said, you probably just want to have a process to update the library with new additions; it looks like they'll be rare.

夏有森光若流苏 2024-08-03 18:57:24

一路扩展方法。 它不会限制你,部分方法只能在程序集中使用,而扩展方法可以在任何地方声明。

Extension methods all the way. It will not limit you, and partial methods can only be used within the assembly, while extension methods can be declared anywhere.

唠甜嗑 2024-08-03 18:57:24

如果您希望它可以在不编译的情况下扩展,您可能需要创建一个单独的转换类。 这将允许您在运行时指定转换并将它们存储在某种形式的字典中,但不幸的是不会有与您键入的内容相同的“内置”语言感觉。

否则,扩展方法可能是您最好的选择 - 但每当您想要添加新转换时,它们都需要重新编译+新库。

If you want this to be extensible without compiling, you probably need to make a separate conversion class. This would allow you to specify the conversions at runtime and store them in some form of dictionary, but unfortunately will not have the same "built-in" langauge feeling as what you were typing.

Otherwise, extension methods are probably your best option - but they will require a recompile + new library anytime you want to add new conversions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文