Skip to main content
 首页 » 编程设计

c#之如何制作具有实现两个接口(interface)的类型约束的通用集合

2024年01月13日32fff_TT

对不起,我没有在 C# 中处理太多泛型

according to this question ,如何制作一个通用集合 实现两个接口(interface) 我一直在寻找像这样的直接方式:当然会出错,而且完全是错误的。

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 

{

不幸的是它不起作用,现在我很困惑,不知道必须做什么,请帮忙,谢谢

请您参考如下方法:

你可以这样做:

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() }; 

这有帮助吗?

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

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

现在您只能将实现这两​​个接口(interface)的东西放入列表中。但不幸的是,C# 中没有这样的功能。对不起!