c# - IEnumerable<> 而不是 List<> 在读取对象时运行良好

标签 c# .net ienumerable

考虑我下面的类(class)专辑:

public class Album
{
    public int? Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Photo> Photos { get; set; }
    public DateTime Registered { get; set; }
}

我可以毫不费力地检索数据并填充我的相册和照片集。

但是现在我还想将照片项目“添加”到我的照片集合中,“添加”未被识别为照片上的有效方法。

'System.Collections.Generic.IEnumerable'does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type....

我应该怎么做才能让它与 IEnumerable 一起工作?我不想将我的属性更改为

public List<Photo> Photos { get; set;}

我真的需要在我的 Album 类上实现 ICollection 吗?

 public class Album : ICollection<Photo> { ... }

最佳答案

如果您不想将属性类型更改为允许添加的类型(IList<Photo>ICollection<Photo>),请添加一个单独的方法来添加图片,如下所示:

public void AddPhoto(Photo p) {
    ...
}

这会让你保留 IEnumerable<Photo>作为您的属性(property)的类型,并且还允许验证调用者输入的内容。例如,您的代码将能够检测照片是否太大或太小,并抛出异常。如果你公开 IList<Photo>,这将很难做到。 ,因为您需要提供自己的实现来覆盖 Add .

您还应该将自动属性的 setter 设为私有(private),或者将自动属性替换为 getter + 支持字段。

关于c# - IEnumerable<> 而不是 List<> 在读取对象时运行良好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16623619/

相关文章:

c# - 如何在字段包含 char ' 的 Access 中运行查询

c# - 属性引用的列表/集合

c# - ASP 转发器从 div 溢出

.net - SQL Server DateDiff 与 .Net DateDiff

c# - 如何使用发送键将 Ctrl+Shift+F1 发送到应用程序

.net - 如何在 VB.NET 中设置字体类对象的颜色?

c# - .NET IL .maxstack 指令如何工作?

c# - 具有公共(public)字段的不同类之间的 IEnumerable.Except()

c# - 如何调用 IEnumerable 函数

c# - 如何将List<List<Int32>>的初始化简化为IEnumerable<IEnumerable<Int32>>?