其中t:多个类 [英] where t : multiple classes

查看:100
本文介绍了其中t:多个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<T> Foo<T>(Ilist list) 
where T : ??



有没有办法强制执行T可将结果
几节课之一吗?

is there any way to enforce T to be
one of few classes ?

我最终想要做对T开关。

eventually i want to do a switch on T..

感谢。

推荐答案

在这种方式强制类型约束指出,那些几类与通用功能有关。

Enforcing a type constraint in this way indicates that those several classes are related with common functionality.

你应该实现一个共同的接口,然后限制类型的接口:

You should implement a common Interface and then restrict the type to that Interface:

public interface IUseful
{
    public void UsefulMethod();
}

List<T> Foo<T>(IList list) where T : IUseful
{
    // You now have access to all common functionality defined in IUseful
}

额外的好处是,现在你不必打开 T 实施不同的行为。你可以有 IUseful 的孩子实现自己的行为,然后调用每一个自己。

The added benefit is that now you don't have to switch on T to implement different behaviors. You can have the children of IUseful implement their own behaviors and then call each on their own.

这篇关于其中t:多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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