abstract class CustomControl : UserControl
{
protected abstract int DoStuff();
}
class DetailControl : CustomControl
{
protected override int DoStuff()
{
// do stuff
return result;
}
}
我在表单中放置了 DetailControl。它在运行时正确呈现,但设计器显示错误并且不会打开,因为基本用户控件是抽象的。
目前,我正在考虑以下补丁,这对我来说似乎是非常错误的,因为我希望子类被迫实现该方法。
class CustomControl : UserControl
{
protected virtual int DoStuff()
{
throw new InvalidOperationException("This method must be overriden.");
}
}
class DetailControl : CustomControl
{
protected override int DoStuff()
{
// do stuff
return result;
}
}
有人对如何解决这个问题有更好的想法吗?
我们想要什么
首先,让我们定义最终类和抽象基类。
public class MyControl : AbstractControl
...
public abstract class AbstractControl : UserControl // Also works for Form
...
现在我们需要的是描述提供者.
public class AbstractControlDescriptionProvider<TAbstract, TBase> : TypeDescriptionProvider
{
public AbstractControlDescriptionProvider()
: base(TypeDescriptor.GetProvider(typeof(TAbstract)))
{
}
public override Type GetReflectionType(Type objectType, object instance)
{
if (objectType == typeof(TAbstract))
return typeof(TBase);
return base.GetReflectionType(objectType, instance);
}
public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args)
{
if (objectType == typeof(TAbstract))
objectType = typeof(TBase);
return base.CreateInstance(provider, objectType, argTypes, args);
}
}
最后我们只需应用一个TypeDescriptionProvider
抽象控件的属性。
[TypeDescriptionProvider(typeof(AbstractControlDescriptionProvider<AbstractControl, UserControl>))]
public abstract class AbstractControl : UserControl
...
就是这样。无需中间控制。
在同一个解决方案中,提供程序类可以应用到我们想要的任意多个抽象基。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)