如何处理GetDataPresent让它接受所有派生类型 [英] How to deal with GetDataPresent to let it accept all the derived types
问题描述
我正在使用 drgevent.Data.GetDataPresent 来确定是否拖动的组件是可接受的。
I'm using drgevent.Data.GetDataPresent to determine whether the dragged component is acceptable or not.
我有一个问题,我想接受一个特定的类型,说SomeType和从它派生的所有类型。似乎 GetDataPresent
不支持这样的要求。
I've got a problem which is that I want to accept a specific type say SomeType and all the types that derived from it. Seems GetDataPresent
doesn't support such requirement.
任何想法?
推荐答案
只是不要使用GetDataPresent(),它是样板,但你可以自由地做你的方式。实际检索对象并检查您是否对其类型感到满意:
Just don't use GetDataPresent(), it is boilerplate but you're free to do it your way. Actually retrieve the object and check if you're happy with its type:
protected override void OnDragEnter(DragEventArgs drgevent) {
var obj = drgevent.Data.GetData(drgevent.Data.GetFormats()[0]);
if (typeof(Base).IsAssignableFrom(obj.GetType())) {
drgevent.Effect = DragDropEffects.Copy;
}
}
其中Base是基类的名称。虽然使用GetFormats()看起来很奇怪,但是这种方法是有保证的,因为拖动.NET对象只能生成一个格式,即对象类型的显示名称。这也是GetDataPresent无法为派生对象工作的原因。
Where Base is the name of the base class. While the use of GetFormats() looks odd, this approach is guaranteed to work because dragging a .NET object only ever produces one format, the display name of the type of the object. Which is also the reason that GetDataPresent can't work for derived objects.
这篇关于如何处理GetDataPresent让它接受所有派生类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!