简体   繁体   中英

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. 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. "

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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