接口的通用类型约束? [英] Generic type constraint for interface?

查看:117
本文介绍了接口的通用类型约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以这样做:

void MyMethod<T>() where T : class { }

有这样的东西吗?

void MyMethod<T>() where T : interface { }

我不希望明确指定接口名称.

I'd prefer not to specify the interface name explicitly.

另一种选择是,我可以传入受class约束的参数,并在typeof(T).IsInterface返回false时引发异常,但这并不像约束那样干净.

The alternative is that I can pass in an argument that's constrained by class and throw an exception if typeof(T).IsInterface returns false, but that's not as clean as a constraint.

推荐答案

这没有任何意义,因为它不会导致任何限制.

This makes no sense since it doesn't leads to any limitations.

约束class表示类型参数必须是引用类型.

Constraint class means that the type argument must be a reference type.

那么没有显式接口名称的interface应该限制什么呢?

So what interface without explicit interface name should limit?

接口本身只是方法/属性的声明,因此约束条件某物是接口"的字面意思是某物具有某些声明",这是没有用的.

Interface itself is just a declaration of methods/properties, so constraint "something is interface" literally mean "something has some declarations" - that is useless.

这篇关于接口的通用类型约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆