我读过很多关于“不公开泛型”的文章,但我仍然没有得到确切的解析度。我编写了一个示例控制台应用程序,它分别使用List和List作为返回类型和参数。在运行代码分析时,它说不公开泛型列表。正如msdn所说
System.Collections.Generic.List<T>是一个为性能而设计的泛型集合,而不是继承。System.Collections.Generic.List<T>不包含使更改继承类的行为更容易的虚拟成员。以下泛型集合是为继承而设计的,应该公开而不是公开System.Collections.Generic.List<T>。
而修正是
若要修复违反此规则的问题,请将
System.Collections.Generic.List<T>类型更改为设计用于继承的泛型集合之一。
如果我使用System.Collections.Generic.ICollection<T>。即使在函数调用之后,我仍然能够添加项。那么泛型集合的用途是什么。以下是代码:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public static List<Person> AddPersonsToCurrentList(List<Person> personsList )
{
personsList.Add(new Person(){ Age = 11, Name = "Vijay" });
return personsList;
}
}
public class Program
{
public static void Main(string[] ar)
{
var personList = new List<Person>()
{
new Person(){Age =10,Name="Vj"}
};
var resultList = Person.AddPersonsToCurrentList(personList);
Console.WriteLine(personList.GetType());
personList.Add(new Person(){Age = 11, Name = "Ajay"});
Console.ReadKey();
}
}现在,如果我将返回类型更改为Collection<Person>,参数更改为Collection<Person>,则输出是相同的。在公开泛型列表时,我将返回类型和参数列表更改为ICollection<Person>/IEnumerable。如果我把ICollection。我仍然能够添加项目后的方法也。修改后的守则:
public static ICollection<Person> AddPersonsToCurrentList(Collection<Person> personsList )
{
personsList.Add(new Person(){ Age = 11, Name = "Vijay" });
return personsList;
}但是,我仍然公开了泛型集合,用户仍然可以在调用方法之前或之后添加项。请任何人帮助我,在性能和其他各种属性方面,List<T>与Collection<T>相比是如何有用的。
这对我会有很大帮助。提前感谢
发布于 2019-02-04 10:28:46
有人警告您,List对象是不灵活的,并且约束外部开发人员使用该具体类型。通常,在开发供其他开发人员使用的代码时,最佳实践是要求尽可能抽象的实现,只实现方法中所需的功能。
这允许最终用户在需要的情况下提供自己的实现。例如,如果您在方法中所做的全部工作是通过列表枚举,则可以不需要List<Person>类型,而是依赖于IEnumerable<Person>。
这为您的API用户提供了实现他们自己的列表类型/帮助程序的灵活性,并且只要他们继承了IEnumerable (这是一项保证您可以通过类型枚举的契约),他们仍然可以正常工作。
在您的示例中,您需要一个类型T的列表,或者从类型T列表继承的内容,并且警告您不要将具体类型的List<T>用于继承。
https://stackoverflow.com/questions/54513662
复制相似问题