使用转换运算符对集合进行类型转换
下面的代码给了我用户定义的转换必须转换为封闭类型或从封闭类型转换,而代码段 #2 则没有...似乎 用户定义的转换例程必须与包含该例程的类相互转换。
我有哪些替代方案?显式运算符作为扩展方法?还要别的吗?
public static explicit operator ObservableCollection<ViewModel>(ObservableCollection<Model> modelCollection)
{
var viewModelCollection = new ObservableCollection<ViewModel>();
foreach (var model in modelCollection)
{
viewModelCollection.Add(new ViewModel() { Model = model });
}
return viewModelCollection;
}
片段 #2
public static explicit operator ViewModel(Model model)
{
return new ViewModel() {Model = model};
}
提前致谢!
The below code gives me User-defined conversion must convert to or from enclosing type, while snippet #2 doesn't... It seems that a user-defined conversion routine must convert to or from the class that contains the routine.
What are my alternatives? Explicit operator as extension method? Anything else?
public static explicit operator ObservableCollection<ViewModel>(ObservableCollection<Model> modelCollection)
{
var viewModelCollection = new ObservableCollection<ViewModel>();
foreach (var model in modelCollection)
{
viewModelCollection.Add(new ViewModel() { Model = model });
}
return viewModelCollection;
}
Snippet #2
public static explicit operator ViewModel(Model model)
{
return new ViewModel() {Model = model};
}
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议您使用以下方法转换集合:
如果您喜欢扩展,您可以定义类似的内容(以避免先前代码中的新内容):
或者也许,一次完成所有操作:
显然,所有先前的代码都可以工作,如果你已经定义了代码片段 #2
I'd suggest you to convert the collection using:
If you like exstensions you could define something like (to avoid the new in the previous code):
Or maybe, to do everything in one shot:
Obviously all the previous codes, will work if you have defined the snippet #2
您的第一个代码片段应该作为 observablecollection 类的 udc 工作。
Your first code snippet should work as a udc on the observablecollection class.