在 C# 中使用泛型
我在 Silverlight 4 MVVM 项目中有以下内容。 我的视图模型中有多种方法,例如 DeleteTeacher(p)、DeleteRecordOfEntity2(p) 等,可以从教师集合中删除教师等。
我希望能够通过传递不同的实体类型来调用 DeleteMyData 方法,如下所示: DeleteMyData<学生>(); DeleteMyData<老师>();
我如何在以下方法中动态更改 this.SelectedTeacher 和 this._myModel.DeleteTeacher(p) 来处理不同的实体和不同的选定对象。
private void DeleteMyData<T>() where T : Entity
{ this.ModalDialogWorker.ShowDialog<T>(
this.ModalDialog, this.CustomControl, this.SelectedTeacher, p =>
{
if (this.ModalDialog.DialogResult.HasValue &&
this.ModalDialog.DialogResult.Value)
{
this._myModel.DeleteTeacher(p);
this._myModel.SaveChangesAsync();
}
});
}
I have the following in a Silverlight 4 MVVM project.
I have several methods such as DeleteTeacher(p), DeleteRecordOfEntity2(p),... etc in my viewmodel which can delete, for example, a teacher from a teachers collection.
I want to be able to call the DeleteMyData method by passing different entity types like so :
DeleteMyData<Student>();
DeleteMyData<Teacher>();
How can i dynamically alter the this.SelectedTeacher and this._myModel.DeleteTeacher(p) in the following method to handle different entities and diferent selected objects.
private void DeleteMyData<T>() where T : Entity
{ this.ModalDialogWorker.ShowDialog<T>(
this.ModalDialog, this.CustomControl, this.SelectedTeacher, p =>
{
if (this.ModalDialog.DialogResult.HasValue &&
this.ModalDialog.DialogResult.Value)
{
this._myModel.DeleteTeacher(p);
this._myModel.SaveChangesAsync();
}
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有一个简单的方法。您可以尝试反射或比较丑陋的 switch 语句中的类型名称。
但为什么不直接为各种对象创建重载呢?
然后在适当的地方调用它:
编辑:再次查看您的示例后,您还可以传入处理删除的委托。您的签名更改为:
然后您可以像这样使用它:
也就是说,我仍然更喜欢重载。 :)
There is not a straightforward way. You could attempt reflection or compare the type names in an ugly switch statement.
But why not just create overloads for the various objects?
Then call it where appropriate:
Edit: After looking at your example again, you can also pass in a delegate that handles the deleting. Your signature changes to:
And then you can use it like:
That said, I still like the overloads better. :)