我想写一个会创建另一个类的不可变副本的类,而我这样做的方式要求副本在构造函数中获取日期和原始实例。我知道你不能创建一个指定参数的构造函数约束,但有没有办法使用代码契约解决它?
public class Copier<o, c>
where o : class, INotifyPropertyChanged
where c : class, c // ideally new(datetime, o)
{
private Dictionary<DateTime, c> copies;
public Copier(o original)
{
this.copies = new Dictionary<DateTime, c>();
original.PropertyChanged +=
this.propertyChangedHandler(object sender, PropertyChangedEventArgs args);
}
private void propertyChangedHandler(object sender, PropertyChangedEventArgs args)
{
var original = sender as o;
var now = DateTime.Now;
this.copies.Add(now, new c(now, original)); // error here
}
}
复制clases是由我创建的,从原件继承,覆盖所有属性为readonly并从构造函数中复制原始值。
注意:有一项要求(由我强加)无法修改原始对象。
答案 0 :(得分:1)
根据建议,传递创建委托:
public class Copier<o, c>
where o : class, INotifyPropertyChanged
where c : class, c // ideally new(datetime, o)
{
private Dictionary<DateTime, c> copies;
private Func<o, DateTime, c> copyFunc;
public Copier(o original, Func<o, DateTime, c> copyFunc)
{
this.copyFunc = copyFunc;
this.copies = new Dictionary<DateTime, c>();
original.PropertyChanged +=
this.propertyChangedHandler(object sender, PropertyChangedEventArgs args);
}
private void propertyChangedHandler(object sender, PropertyChangedEventArgs args)
{
var original = sender as o;
var now = DateTime.Now;
this.copies.Add(copyFunc(now, original));
}
}