如何在通用设置中使用类型(=静态)成员
我想就静态方法/属性签订合同,以便在通用设置中使用它们。像这样:
interface IAnimal {
static string Sound;
}
class Dog : IAnimal {
static string Sound => "woof";
}
class Cat : IAnimal {
static string Sound => "meow";
}
class AnimalSoundExplainer<T> where T : IAnimal {
// This does not work (but I would like it to):
internal static void Explain() =>
Console.WriteLine("Every " + typeof(T).Name + " makes " + T.Sound);
}
我会这样使用它:
AnimalSoundExplainer<Dog>.Explain(); // should write "Every Dog makes woof"
AnimalSoundExplainer<Cat>.Explain(); // should write "Every Cat makes meow"
我如何制定该合同(这样,如果我不履行合同,我会收到编译错误)? C# 的静态接口成员不是这样工作的; C# 将始终仅使用(提供或未提供)IAnimal 的实现。它确实允许实现/覆盖类似于非静态成员的静态成员。
如何在通用设置中使用该约定,即如何从给定的通用类型参数访问这些成员
- 而不需要生成实例,
- 也不使用使我的程序变慢的反射方法? (如果有反射方法不会使我的程序变慢,我会同意它们。)
I want to make a contract about static methods/properties in order to use them in a generic setting. Like this:
interface IAnimal {
static string Sound;
}
class Dog : IAnimal {
static string Sound => "woof";
}
class Cat : IAnimal {
static string Sound => "meow";
}
class AnimalSoundExplainer<T> where T : IAnimal {
// This does not work (but I would like it to):
internal static void Explain() =>
Console.WriteLine("Every " + typeof(T).Name + " makes " + T.Sound);
}
I would use it like this:
AnimalSoundExplainer<Dog>.Explain(); // should write "Every Dog makes woof"
AnimalSoundExplainer<Cat>.Explain(); // should write "Every Cat makes meow"
How can I make that contract (so that I get compile errors if I do not fulfill the contract)? C#'s static interface members do not work that way; C# will always just use the (provided or not) implementation of
IAnimal
. It does allow implementing/overriding static members analog to non-static members.How can I make use of that contract inside a generic setting, i.e. how can I access theses members from a given generic type argument
- without needing to generate instances and
- without using reflection methods that make my program slow?
(If there are reflection methods that do not make my program slow, I'd be okay with them.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此功能称为“ “,它是当前正在预览中.net 6 。
If you're happy enabling preview functionality, the following works in .NET 6 preview:
See它在sharplab上。
This functionality is called "static abstract members", and it is currently in preview in .NET 6.
If you're happy enabling preview functionality, the following works in .NET 6 preview:
See it on SharpLab.