简体   繁体   English

在接口中创建通用List属性

[英]Create generic List property in interface

I need to make an interface like this: 我需要创建一个这样的界面:

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

And then implement it like this: 然后像这样实现它:

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

Or like this: 或者像这样:

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

But looking at other posts it seems like I have to define T in top of my interface class. 但是看看其他帖子 ,似乎我必须在接口类的顶部定义T. Which forces me to one specific type for all properties when implementing. 在实施时,这迫使我为所有属性的一个特定类型。 Can this be done somehow? 这可以以某种方式完成吗?

Thanks 谢谢

You can make the interface generic, with a type argument for each property that requires a different type, for example: 您可以使接口具有通用性,并为每个需要不同类型的属性使用类型参数,例如:

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

And use it like this: 并像这样使用它:

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

"But looking at other posts it seems like I have to define T in top of my interface class. Which forces me to one specific type for all properties when implementing. " “但是看看其他帖子,似乎我必须在接口类的顶部定义T。这会强制我在实现时为所有属性指定一种特定类型。”

True. 真正。 But you may define as many generic parameters as you want , not only a single. 但是您可以根据需要定义任意数量的通用参数 ,而不仅仅是单个参数。 So in your case this should do it: 所以在你的情况下,这应该这样做:

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

Now you can provide two completely independent types: 现在您可以提供两种完全独立的类型:

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

You could use 你可以用

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

So when you define your class, it'd be 因此,当你定义你的课时,它就是

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

Try this code. 试试这个代码。

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM