如何将接口用作 C# 泛型类型约束? [英] How can I use interface as a C# generic type constraint?
问题描述
有没有办法得到下面的函数声明?
Is there a way to get the following function declaration?
public bool Foo<T>() where T : interface;
即.其中 T 是接口类型(类似于 where T : class
和 struct
).
ie. where T is an interface type (similar to where T : class
, and struct
).
目前我已经解决了:
public bool Foo<T>() where T : IBase;
其中 IBase 被定义为一个空接口,它被我所有的自定义接口继承......不理想,但它应该可以工作......你为什么不能定义泛型类型必须是接口?
Where IBase is defined as an empty interface that is inherited by all my custom interfaces... Not ideal, but it should work... Why can't you define that a generic type must be an interface?
对于它的价值,我想要这个,因为 Foo
在需要接口类型的地方进行反射......我可以将它作为普通参数传入并在函数本身中进行必要的检查,但这似乎更类型安全(而且我认为性能更高一些,因为所有检查都是在编译时完成的).
For what it's worth, I want this because Foo
is doing reflection where it needs an interface type... I could pass it in as a normal parameter and do the necessary checking in the function itself, but this seemed a lot more typesafe (and I suppose a little more performant, since all the checks are done at compiletime).
推荐答案
最接近你能做的(除了你的基本接口方法)是where T : class
",意思是引用类型.没有表示任何接口"的语法.
The closest you can do (except for your base-interface approach) is "where T : class
", meaning reference-type. There is no syntax to mean "any interface".
此(where T : class
")用于,例如,在 WCF 中将客户端限制为服务合同(接口).
This ("where T : class
") is used, for example, in WCF to limit clients to service contracts (interfaces).
这篇关于如何将接口用作 C# 泛型类型约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!