简体   繁体   English

使用ICollection而不是List

[英]Use ICollection instead of List

I have an external method which returns List<IPAddress> 我有一个返回List<IPAddress>的外部方法

I write in my class other method which is a wrapper for that. 我在我的课堂上写了另一种方法,它是一个包装器。 But I was told to not return List<> ,but IList or ICollection . 但我被告知不要返回List<> ,而是IListICollection For now what I have : 现在我拥有的东西:

MyClass obj = new MyClass();
List<IPAddress> addr = obj.GetAddr();//GetAddr() now return `List`,but should be changed to return ILIst or ICollection

What should I do - casting? 我该怎么办 - 铸造?

Upd I did what you said and get an errr "can`t implicitly convert Ilst to List (It is .net 4.5) 更新我做了你所说的并得到一个错误“无法隐式地将Ilst转换为List(它是.net 4.5)

What he/she probably meant is: return the list as an IList<T> or ICollection<T> . 他/她可能的意思是:将列表作为 IList<T>ICollection<T>

In order to do that, simply change your method's signature and return the list as you normally would: 为此,只需更改方法的签名并按照通常的方式返回列表:

public ICollection<T> Method(){
    MyClass obj = new MyClass();
    List<IPAddress> addr = obj.GetAddr();

    return addr;
}

This is to avoid binding your client's to a concrete List<T> implementation. 这是为了避免将客户端绑定到具体的List<T>实现。

By returning something more abstract, like an ICollection<T> , or even an IEnumerable<T> , you won't run into any problems if you later decide to use a HashSet<T> instead of a List<T> internally. 通过返回更抽象的东西,比如ICollection<T> ,甚至是IEnumerable<T> ,如果你以后决定在内部使用HashSet<T>而不是List<T> ,你将不会遇到任何问题。 The signature and the client's code will remain the same. 签名和客户端代码将保持不变。

You can change the method return type to IList<IPAddress> or IEnumerable<IPAddress> like: 您可以将方法返回类型更改为IList<IPAddress>IEnumerable<IPAddress>如:

public IList<IPAddress> GetAddress()
{
    return new List<IPAddress>(); //replace with your code to return list
}

public IEnumerable<IPAddress> GetAddress()
{
    return new List<IPAddress>(); //replace with your code to return list
}

Just change the return value of the method. 只需更改方法的返回值即可。 Since List is implicitly convertible to both interfaces, there is no need for any cast. 由于List可以隐式转换为两个接口,因此不需要任何转换。

If obj.GetAddr() returns IList<IPAddress> , ICollection<IPAddress> , or IEnumerable<IPAddress> , all you need to do is add .ToList() to the end of your assignment: 如果obj.GetAddr()返回IList<IPAddress>ICollection<IPAddress>IEnumerable<IPAddress> ,那么您需要做的就是将.ToList()添加到作业的末尾:

List<IPAddress> addr = obj.GetAddr().ToList();

Or, you can follow the current convention of not explicitly typing your variables, and just do the following: 或者,您可以遵循当前不明确键入变量的约定,并执行以下操作:

var addr = obj.GetAddr();

This will then allow you to maintain your addr variable as whatever return type your GetAddr() method returns. 这将允许您将addr变量维护为GetAddr()方法返回的任何返回类型。 You will still have access to all the properties of that return type. 您仍然可以访问该返回类型的所有属性。

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

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