开发者

Using generics in C#

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 ha开发者_运维百科ndle 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();
                    }
                });

        }


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?

private void DeleteMyData(Teacher teacher) { /* Delete Teacher code */ }

private void DeleteMyData(Student student) { /* Delete Student code */ }

Then call it where appropriate:

private void DeleteMyData(this.SelectedTeacher);

Edit: After looking at your example again, you can also pass in a delegate that handles the deleting. Your signature changes to:

private void DeleteMyData<T>(T value, Action<T> deleteAction)
{
    this.ModalDialogWorker.ShowDialog<T>(
        this.ModalDialog, this.CustomControl, value, p =>
        {
            if ( this.ModalDialog.DialogResult.HasValue &&
                this.ModalDialog.DialogResult.Value )
            {
                deleteAction( p );
                this._myModel.SaveChangesAsync();
            }
        } );
}

And then you can use it like:

DeleteMyData( this.SelectedTeacher, this._myModel.DeleteTeacher );

DeleteMyData( this.SelectedStudent, this._myModel.DeleteStudent );

That said, I still like the overloads better. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜