有没有办法强制C#类来实现某些静态函数?没有办法、来实现、静态、函数

2023-09-02 11:58:15 作者:孤独是我妻

我开发了一组类实现一个共同的接口。一个消费者我的图书馆应指望每个类实现一组特定的静态函数。反正是有,我可以装饰这些类,以便编译器将捕获,其中未实现的功能之一的情况下。

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.

我知道构建消费code时,它最终会被抓到。而且我也知道了如何使用一种工厂类来解决这个问题。

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 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:

使用反射在运行时;交叉手指和希望...... 使用一个单/默认实例/类似于实现该声明的方法接口

(更新)

其实,只要你有单元测试,第一个选项实际上不是那么糟糕,因为你可能会想,如果(像我一样),你从一个严格的静态类型的背景。事实是;它工作正常的动态语言。事实上,这正是我的通用的运营商 code工作 - 它希望的你有静态的运营商。在运行时,如果你不这样做,就会嘲笑你在适当嘲讽的语气...但它不能检查在编译时。

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.