我可以使用代码契约来解决无法使用通用构造函数约束的问题吗?
我正在编写一个类,该类将创建另一个类的不可变副本,而我这样做的方式要求该副本在构造函数中采用日期和原始实例。我知道您无法创建指定参数的构造函数约束,但是有没有办法使用代码契约来解决它?
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
}
}
复制类是我创建的,继承自原始类,将所有属性覆盖为只读,并在构造函数中复制原始类的值。
注意:有一个要求(由我强加),原始对象不能被修改。
I'm tying to write a class that will create immutable copies of another class, and the way I'm doing it requires that the copy takes a date and an instance of the original in the constructor. I know that you can't create a constructor constraint that specifies parameters, but is there a way to work around it using code contracts?
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
}
}
The copy clases are created by me, inherit from the originals, override all of the properties to readonly and copy the values from the original in the constructor.
Note: There is a requirement (imposed by me) that the original objects cannot be modified.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
按照建议,传递创建委托:
}
As suggested, pass a creation delegate:
}