考虑我下面的类(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/