创建界面泛型列表属性

问题描述 投票:2回答:4

我需要这样的接口:

public interface ISomething
{
    List<T> ListA { get; set; }
    List<T> ListB { get; set; }
}

然后实现它是这样的:

public class Something01: ISomething
{
    public List<string> ListA { get; set; }
    public List<Person> ListB { get; set; }
}

或者是这样的:

public class Something02: ISomething
{
    public List<int> ListA { get; set; }
    public List<string> ListB { get; set; }
}

但看other posts好像我在接口类的顶部定义吨。其实施的时候迫使我一个特定类型的所有属性。可以这样做不知何故?

谢谢

c#
4个回答
4
投票

您可以使接口通用,与需要不同类型,例如每个属性类型参数:

public interface ISomething<TA, TB>
{
    List<TA> ListA{ get; set; }
    List<TB> ListB {get; set; }
}

并使用它像这样:

public class Something01: ISomething<string, Person>
{
    public List<string> ListA { get; set; }
    public List<Person> ListB { get; set; }
}

2
投票

“但看着其他职位,好像我在接口类的顶部定义吨。这迫使我去一个特定类型的实现时,所有的属性。”

真正。但是,只要你想,不仅是单一的,你可以定义为许多通用的参数。所以你的情况这应该这样做:

public interface ISomething<T, S>
{
    List<T> ListA{ get; set; }
    List<S> ListB {get; set;}
}

现在,您可以提供两个完全独立的类型:

class MyClass : ISomething<Type1, Type2> { ... }

1
投票

你可以使用

public interface ISomething<T, U>
{
    List<T> ListA{ get; set; }
    List<U> ListB {get; set;}
}

所以,当你定义你的类,它会是

public class Something : ISomething<Person, string>
{
    List<Person> ListA{ get; set; }
    List<string> ListB {get; set;}
}

1
投票

试试这个代码。

public interface ISomething<T, K>
  {
    List<T> ListA { get; set; }
    List<K> ListB { get; set; }
  }

  public class Something01 : ISomething<string, Person>
  {
    public List<string> ListA { get; set; }
    public List<Person> ListB { get; set; }
  }
© www.soinside.com 2019 - 2024. All rights reserved.