Winforms 如何从DragEventArgs确定数据类型

Winforms 如何从DragEventArgs确定数据类型,winforms,drag-and-drop,Winforms,Drag And Drop,我已经在我的应用程序中实现了拖放,但是在确定要拖动的对象的类型时遇到了一些困难。我有一个基类指示符和几个派生自它的类。拖动的对象可以是这些类型中的任何一种。下面的代码片段看起来不雅观,容易出现维护问题。每次我们添加一个新的派生类时,我们都必须记住触摸这段代码。看起来我们应该可以在这里使用继承 protected override void OnDragOver(DragEventArgs e) { base.OnDragOver(e); e.Effect = Dra

我已经在我的应用程序中实现了拖放,但是在确定要拖动的对象的类型时遇到了一些困难。我有一个基类
指示符
和几个派生自它的类。拖动的对象可以是这些类型中的任何一种。下面的代码片段看起来不雅观,容易出现维护问题。每次我们添加一个新的派生类时,我们都必须记住触摸这段代码。看起来我们应该可以在这里使用继承

  protected override void OnDragOver(DragEventArgs e)
  {
     base.OnDragOver(e);

     e.Effect = DragDropEffects.None;

     // If the drag data is an "Indicator" type
     if (e.Data.GetDataPresent(typeof(Indicator)) ||
         e.Data.GetDataPresent(typeof(IndicatorA)) ||
         e.Data.GetDataPresent(typeof(IndicatorB)) ||
         e.Data.GetDataPresent(typeof(IndicatorC)) ||
         e.Data.GetDataPresent(typeof(IndicatorD)))
     {
        e.Effect = DragDropEffects.Move;
     }
  }
类似地,我们在使用GetData实际获取拖动对象时也会遇到问题:

protected override void OnDragDrop(DragEventArgs e)
{
    base.OnDragDrop(e);

    // Get the dragged indicator from the DragEvent
    Indicator indicator = (Indicator)e.Data.GetData(typeof(Indicator)) ??
                          (Indicator)e.Data.GetData(typeof(IndicatorA)) ??
                          (Indicator)e.Data.GetData(typeof(IndicatorB)) ??
                          (Indicator)e.Data.GetData(typeof(IndicatorC)) ??
                          (Indicator)e.Data.GetData(typeof(IndicatorD));
}
谢谢。

方法如下:

返回存储在此实例中的数据与之关联或可转换为的所有格式的列表

这是一个
字符串数组

String[] allFormats = myDataObject.GetFormats();

然后,您可以检查该列表中的类型,其中一个应该是
指示符

通过显式指定类型来存储数据,即

dataObject.SetData(typeof(Indicator), yourIndicator);

这将允许您仅根据
指示器
类型而不是子类型来检索它。

这就像一个champ!为了完成您的解决方案:在OnMouseDown内部,我曾经有:DoDragDrop(indicator,DragDropEffects.Move);现在,它看起来是这样的:dataobjectd=newdataobject();d、 设置数据(类型(指示器),指示器);DoDragDrop(d,DragDropEffects.Move);