如何使用接口为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;
IE浏览器。其中T是一个接口类型(类似于,其中T:类
和结构
)。
目前我已经定居:
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?
有关它的价值,我想这是因为富
在做反思它需要一个接口类型......我可以把它作为一个正常的参数和做在函数中必要的检查,不过这似乎有更多类型安全的(我想一点更高性能的,因为所有的检查是在编译时完成)。
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).
推荐答案
最近你可以做(除了您的基本接口的方法)为,其中T:类
,意思是引用类型。有没有语法的意思是任何接口。
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".
这(其中T:类
)。使用,例如,在WCF限制客户服务合同(接口)
This ("where T : class
") is used, for example, in WCF to limit clients to service contracts (interfaces).
这篇关于如何使用接口为C#泛型类型的限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!