可能重复:
C# - List <T>或IList <T>
它写的是你应该IList<T>从你的方法返回而不是,List<T>但我找不到任何真正好的理由.我一直在寻找执行此操作的代码,然后调用代码通常执行以下两项操作之一:
new List<T>(returnedIList)它可以使用List上的所有好方法List<T>可以使用List上的所有好方法第一个是笨重的,第二个是抛出(运行时), InvalidCastException如果实现实际上已经改变为其他东西(这使得它完全是愚蠢的).
如果我使用List<T>并且由于某种原因必须将其替换为IList<T>我无法继承的实现,List<T>那么我将得到构建错误并且必须更改一些代码.这可能是非常不可能的,如果发生这种情况,修复工作并不是很多.当然,不值得失去List<T>和/或不得不投射/新List<T>(存在,查找等)的好处,以便让他们回到这种不太可能的情况?
那么,还有其他原因可以归还IList<T>吗?
可能重复:
C# - List <T>或IList <T>
当我从我的方法返回一个列表时,我可以用两种方式完成.作为一个清单
Private List<datatype> MethodName()
{
Return List
}
Run Code Online (Sandbox Code Playgroud)
作为一个IList
Private IList<datatype> MethodName()
{
Return IList
}
Run Code Online (Sandbox Code Playgroud)
我听说我们应该把它作为IList归还.有人能解释为什么吗?
我一直被告知对接口的编程更好,所以我的方法的参数我会设置IList<T>而不是List<T>..
但这意味着我必须施展才能List<T>使用某些方法,Find例如,我想到了一个方法.
为什么是这样?我应该继续针对接口进行编程,还是继续进行转换或还原?
我有点困惑为什么Find(例如)没有继承自IList<T>哪些List<T>.
可能重复:
C# - List <T>或IList <T>
我上课了
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我需要定义一个列表,并以下面的方式定义它之间的区别
IList<Employee> EmpList ;
Or
List<Employee> EmpList ;
Run Code Online (Sandbox Code Playgroud) 我最近阅读了一些关于在暴露集合而不是具体实现时使用接口的东西(IEnumerable而不是List).我现在正试着在我的代码中这样做.但是,当我公开一个返回IEnumerable的属性时,我遇到了一些不允许空值作为返回值的困难.例:
public class HumanResource
{
public IEnumerable<EmployeeModel> Employees
{
get
{
// return what?
}
}
}
Run Code Online (Sandbox Code Playgroud)
我应该在吸气剂中返回什么?我不想为此使用自动属性,因为我想避免空值.我想要的是返回一个没有项目的新集合.当然我可以返回任何实现IEnumerable的类型,但该类的外部用户将如何知道?或者我是否理解这个暴露界面而不是具体的实现错误?
编辑:删除了二传手
我可以从我的DAL返回List吗?在互联网上,我在某处读到它并不好.如果返回List会有什么问题?
我通过一个代码示例,我已经看到了一种不同的方式来创建一个实例.
所以这里的代码
public interface IEmployee
{
System.Int32? EmployeeID { get; set; }
System.String FirstName { get; set; }
System.String LastName { get; set; }
System.DateTime DateOfBirth { get; set; }
System.Int32? DepartmentID { get; set; }
System.String FullName();
System.Single Salary();
}
public class Employee : IEmployee
{
#region Properties
public System.Int32? EmployeeID { get; set; }
public System.String FirstName { get; set; }
public System.String LastName { get; set; }
public System.DateTime DateOfBirth { get; set; }
public System.Int32? DepartmentID …Run Code Online (Sandbox Code Playgroud)