有没有办法强制 C# 类实现某些静态函数? [英] Is there a way to force a C# class to implement certain static functions?
问题描述
我正在开发一组实现通用接口的类.我的库的使用者应该期望这些类中的每一个都实现一组特定的静态函数.无论如何,我可以装饰这些类,以便编译器捕获未实现其中一个函数的情况.
I am developing a set of classes that implement a common interface. A consumer of my library shall expect each of these classes to implement a certain set of static functions. Is there anyway that I can decorate these class so that the compiler will catch the case where one of the functions is not implemented.
我知道它最终会在构建消费代码时被捕获.而且我也知道如何使用一种工厂类来解决这个问题.
I know it will eventually be caught when building the consuming code. And I also know how to get around this problem using a kind of factory class.
只是想知道是否有任何语法/属性要求在类上使用静态函数.
Just curious to know if there is any syntax/attributes out there for requiring static functions on a class.
Ed 删除了界面"一词以避免混淆.
Ed Removed the word 'interface' to avoid confusion.
推荐答案
不,C# 中没有对此的语言支持.我可以立即想到两种解决方法:
No, there is no language support for this in C#. There are two workarounds that I can think of immediately:
- 在运行时使用反射;交叉手指和希望...
- 使用单例/默认实例/类似来实现声明方法的接口
(更新)
实际上,只要您进行单元测试,如果(像我一样)您来自严格的静态类型"背景,第一个选项实际上并不像您想象的那么糟糕.事实是;它在动态语言中运行良好.事实上,这正是我的泛型运算符代码的工作原理 - 它希望你有静态操作符.在运行时,如果您不这样做,它会以适当的嘲讽语气嘲笑您……但它无法在编译时检查.
Actually, as long as you have unit-testing, the first option isn't actually as bad as you might think if (like me) you come from a strict "static typing" background. The fact is; it works fine in dynamic languages. And indeed, this is exactly how my generic operators code works - it hopes you have the static operators. At runtime, if you don't, it will laugh at you in a suitably mocking tone... but it can't check at compile-time.
这篇关于有没有办法强制 C# 类实现某些静态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!