题
我有一个Email
对象和在尝试验证在其List<Attachment>
属性附件的数量。
诀窍是,我们消耗跨越WCF服务Send()
方法。这很容易验证它的服务器端,但我想先验证它的客户端。
我已经产生,其他人都应该以消耗的服务,这又具有含有的所有对象和可用的方法的代理使用一个库。我想我应该能过载与一些自定义代码的GenericList的Add()
方法,以便添加任何东西时,是集检查,如果超过规定的最大值,然后抛出一个异常。
public partial class List<Attachment>
{
public void Add(Attachment item)
{
base.Add(item);
if (this.Count() > maxAttachments)
{
throw new Exception("fail")
}
}
}
这个不工作 - 我不能类base.Add()和我无法与指定类型定义部分类
。如何创建Add方法的重载,这样我可以包括一些自定义代码?
解决方案
如果您拥有Email
类,你最好的办法是为基础类型的列表成员更改为一个专门的实现列表。
public class Email
{
const int MaxAttachments = /* ... */;
public Email(/* ... */)
{
this.Attachments = new FixedSizeList<Attachment>(MaxAttachments);
}
// ...
public IList<Attachment> Attachments
{
get;
private set;
}
}
class FixedSizeList<T> : IList<T>
{
List<T> innerList;
int maxCount;
public FixedSizeList(int maxCount)
{
this.innerList = new List<T>(maxCount);
this.maxCount = maxCount;
}
// override all the IList<T> members here by delegating
// to your innerList ...
// ...
public void Add(T item)
{
if (this.Count == this.maxSize)
{
throw new InvalidOperationException("No more items can be added.");
}
this.innerList.Add(item);
}
// ...
// ...
}
这是一种大量的样板代码,但是这真的很干净地覆盖这些行为的唯一途径。
不过,如果您不要拥有Email
类,你不能真正做到这一点,通过传统的手段;你需要一个反射黑客更换底层成员或类似的托管扩展框架。
其他提示
List<T>
不是一个局部类,因此,使用你自己的部分类它不能扩展。
另外,LINQ到对象上不Add()
提供List<T>
,这是由IList<T>
实现的List<T>
接口的一部分,并且Add()
不在List<T>
虚拟或抽象方法,所以不能将其覆盖。
你应该看看是System.Collections.ObjectModel.Collection<T>
- 该组件提供了类似于与添加的能力List<T>
覆盖保护的方法,让你的地方做验证任务清单实施
您不必从头开始实现列表中,你只是继承它,并覆盖方法,如InsertItem()
和RemoveItem()
来实现自定义的规则:
using System.Collections.ObjectModel;
public class EmailCollection : Collection<Email>
{
public int MaximumAttachments { get; set; }
protected override void InsertItem(int index, Email item)
{
if (Count == MaximumAttachments)
{
... throw error
}
// do actual insert
base.InsertItem(index, item)
}
}
Add()
引擎盖下调用InsertItem()
。
不隶属于 StackOverflow