如何使用Type Constraint创建实现两个接口的Generic Collection?

时间:2011-01-31 18:02:07

标签: c# syntax generics

对不起我在c#

中没有处理泛型问题

according to this question,如何制作generc集合呢? 实现两个接口 我正在寻找一种这样的直接方式: 当然会出错,完全是错误的。

interface IEmployee {void DisplayInfo();}

interface ISalary {void CalculateSalary();}


class Nurse : IEmployee, ISalary
{
 //some Implementation
}


class Doctor : IEmployee, ISalary
{
 //some Implementation
}

class EntryPoint
{
 static void Main(string[] args)
  { 
  System.Collections.Generic .List<T>  employees where T: ISalary,IEmployee
   =new System.Collections.Generic .List<T>();
  }

 Nurse oNurse = new Nurse();
 Doctor oDoctor = new Doctor();

 employees.Add(oNurse);
 employees.Add(oDoctor);
}
经过一些阅读后,我发现可能我必须首先定义这样的泛型类:

public class HospitalEmployee<T> where T : IEmployee, ISalary

{

}

并且不幸的是它很有效,现在我很困惑,不知道该怎么做,请帮助,谢谢你

3 个答案:

答案 0 :(得分:14)

你可以这样做:

interface IEmployee { void DisplayInfo(); }
interface ISalaried { void CalculateSalary(); }
interface ISalariedEmployee : IEmployee, ISalaried {}
class Doctor : ISalariedEmployee { whatever }
class Nurse : ISalariedEmployee { whatever }
...
var list = new List<ISalariedEmployee>() { new Nurse(), new Doctor() };

这有帮助吗?

基本上真正想要的功能不存在。有一种方法可以说“这个泛型类型参数必须用实现这两个接口的类型参数构造”但奇怪的是,没有办法说“这个局部变量必须使用对实现这两个接口的对象的引用来初始化“。这只是C#类型系统的一个缺点,您可以在类型参数中表示但不能在本地中表示。你想要的是:

var list = new List<IEmployee + ISalary>();

现在你只能把东西放到实现两个接口的列表中。但不幸的是,C#中没有这样的功能。遗憾!

答案 1 :(得分:1)

目前尚不清楚您要做什么:创建自己的通用容器或使用List<T>存储不同的对象。

但据我所知,你需要这样的东西:

List<IEmployee> employees = new List<IEmployee>();
Nurse oNurse = new Nurse();
Doctor oDoctor = new Doctor();

employees.Add(oNurse);
employees.Add(oDoctor);

<强>更新

只需创建一个继承所有想要使用的接口的接口,如:

interface IEmployeeWithSalery: IEmployee, ISalery {}
List<IEmployeeWithSalery> employees = new List<IEmployeeWithSalery>()

答案 2 :(得分:0)

这听起来很像我几周前提出的问题Storing an object that implements multiple interfaces and derives from a certain base (.net)。我提供了一个可能的解决方法,可能比定义和使用一些“组合”接口类型更多的工作,但具有以下优点:可以定义一个对象以使用适当定义的任何特定接口组合,而无需定义该组合的新“组合”界面类型。

相关问题