简体   繁体   English

通用方法,其中 T 是实现接口的列表

[英]Generic Method where T is List that implements interface

This is similar to C# - Multiple generic types in one list这类似于C# - 一个列表中的多个泛型类型

However, I want a generic method to accept a List of objects that all implement the same interface.但是,我想要一个通用方法来接受所有实现相同接口的对象列表。

This code gives the error that there is no implicit reference conversion.此代码给出了没有隐式引用转换的错误。

public interface ITest { }
public class InterfaceUser : ITest { }
public class TestClass
{
    void genericMethod<T>(T myList) where T : List<ITest> { }
    void testGeneric()
    {
        genericMethod(new List<InterfaceUser>());
    }
}

Can this be done?这可以做到吗?

Define T as ITest and take a List<T> as argumentT定义为ITest并将List<T>作为参数

public interface ITest { }
public class InterfaceUser : ITest { }
public class TestClass
{
    void genericMethod<T>(List<T> myList) where T : ITest { }
    void testGeneric()
    {
        this.genericMethod(new List<InterfaceUser>());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 T实现接口的通用方法<T> - Generic method where T implements Interface<T> 在实现通用接口方法的方法中专门化类型 - Specialize type in method that implements a generic interface method 检查对象是否使用通用接口实现接口 <T> 泛型类型是T的子代 - Checking if an object implements an interface with a generic <T> where the generic type is a child of T 转换列表<IInfrastructureEntity>列出<TEntity>其中泛型类型 TEntity 必须实现该接口 - Convert List<IInfrastructureEntity> to List<TEntity> where generic type TEntity necessarily implements that interface 为什么我不能将一个项目转换为泛型类型——其中泛型类型是一个接口,并且在检查该项目是否实现了所述接口之后? - Why can't I cast an item to a generic type — where the generic type is an interface, and after checking that the item implements said interface? 采取实现另一个接口的接口的通用方法,而不调用正确的方法 - Generic Method That Takes an interface that implements another interface, not calling correct method 除非T实现接口I,否则需要通用方法返回类型T,在这种情况下,返回I - Need generic method to return type T unless T implements interface I, in which case return I C#通用接口,通用工具,类型化方法 - C# Generic Interface, Generic Implements, Typed Method 如何创建一个 List(of T),其中 T 是 (T) 的接口,List 的内容继承了一个实现 T 接口的抽象类 - How can I create a List(of T) where T is an interface of (T) and the contents of the List inherit an Abstract class that implements the interface of T 实现接口的泛型还是双精度? - Generic that implements an interface or is a double?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM