如何在C#3.5中的通用方法上放置接口约束? [英] How to put an interface constraint on a generic method in C# 3.5?

查看:88
本文介绍了如何在C#3.5中的通用方法上放置接口约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C#3.5中实现以下目标:

I want to achieve something like this in C# 3.5:

public void Register<T>() : where T : interface {}

我可以使用类或结构,但是如何使用接口呢?

I can do it with class or struct, but how to do it with an interface?

推荐答案

C#和CLR不支持总体接口约束,尽管您可以将其约束到特定接口(请参见其他答案) )。恐怕您能获得的最接近的是类,并在运行时使用反射检查类型。为什么首先要有接口约束?

C# and the CLR don't support overall interface constraints, although you can constrain it to a particular interface (see other answers). The closest you can get is 'class' and check the type using reflection at runtime I'm afraid. Why would you want an interface constraint in the first place?

这篇关于如何在C#3.5中的通用方法上放置接口约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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