是否可以使此方法通用

dem*_*mas 3 c# generics

我有一个实现一些接口的类:

public interface IMyInterface
{  
    string GetKey();
    void SetData(List<int> data);
}

public class A : IMyInterface { .. }
public class B : IMyInterface { .. }
Run Code Online (Sandbox Code Playgroud)

我有一个方法可以获取这些类的集合并做同样的事情:

public void methodA(List<A> items)
{
    foreach(var item in items)
    {     
         // do something with A.GetKey();
         // do something with A.SetData();
    }
}

public void methodB(List<B> items)
{
    foreach(var item in items)
    {     
         // do something with B.GetKey();
         // do something with B.SetData();
    }
}
Run Code Online (Sandbox Code Playgroud)

我想使这个方法通用:

public GenericMethod<T>(T items) where T: IEnumerable
{
    for(var item in items)
    {
        // how can I get the item.GetKey();
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎么能对编译器说T:Inumerable的元素实现IMyInterface并且有方法GetKey()?

Sho*_*eel 6

你可以这样做:

public void GenericMethod<T>(IEnumerable<T> items)
    where T : IMyInterface
{
    for(var item in items)
    {
       // how can I get the item.GetKey();
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然在目前的情况下,你真的不需要泛型使用tihs:

public void GenericMethod(IEnumerable<IMyInterface> items)
{
    for(var item in items)
    {
       // how can I get the item.GetKey();
    }
}
Run Code Online (Sandbox Code Playgroud)