C# 用户控制开关
有两个不同的UserControl,它们共享一些公共属性。 我想做的是根据一个外部标志在这两者之间切换C# 用户控制开关,c#,user-controls,C#,User Controls,有两个不同的UserControl,它们共享一些公共属性。 我想做的是根据一个外部标志在这两者之间切换 UserControl u1, u2; if(flag) { u1 = u1 as ControlType1; u2 = u2 as ControlType1; } else { u1 = u1 as ControlType2; u2 = u2 as ControlType2; } SomeMethod(u1.SelectedItemName, u2.Sel
UserControl u1, u2;
if(flag)
{
u1 = u1 as ControlType1;
u2 = u2 as ControlType1;
}
else
{
u1 = u1 as ControlType2;
u2 = u2 as ControlType2;
}
SomeMethod(u1.SelectedItemName, u2.SelectedItemName);
由于UserControl没有名为“SelectedItemName”的属性,因此代码不会抛出错误
我目前所做的是,我在UserControl上添加了一个扩展方法,该方法使用反射获取“SelectedItemName”,我通过调用u1.SelectedItemName()而不是u1.SelectedItemName来获取值
我的问题是,不使用扩展/也许是正确的方法,什么是解决这个问题的简单方法。请注意,我不想在if语句中重复SomeMethod(a,b)。试试这个isntead:
UserControl u1, u2;
if(flag)
{
u1 = u1 as ControlType1;
u2 = u2 as ControlType1;
SomeMethod((u1 as ControlType1).SelectedItemName, (u2 as ControlType1).SelectedItemName);
}
else
{
u1 = u1 as ControlType2;
u2 = u2 as ControlType2;
SomeMethod((u1 as ControlType2).SelectedItemName, (u2 as ControlType2).SelectedItemName);
}
或者,如果您创建一个BaseControlType
,其中包含SelectedItemName
,并且ControlType1
和ControlType2
从中扩展,您可以执行以下操作:
UserControl u1, u2;
if(flag)
{
u1 = u1 as ControlType1;
u2 = u2 as ControlType1;
}
else
{
u1 = u1 as ControlType2;
u2 = u2 as ControlType2;
}
SomeMethod((u1 as BaseControlType).SelectedItemName, (u2 as BaseControlType).SelectedItemName);
我的建议是让这两个
UserControl
类实现一个共享接口或派生自一个共享基类。然后,您可以针对基类或接口进行开发,而不必担心标志/开关
IYourUserControl u1, u2;
SomeMethod(u1, u2);
如果某种方法被定义为:
void SomeMethod(IYourUserControl one, IYourUserControl two) { // ...
我只是补充说,我不想重复SomeMethod()两次;很抱歉没有添加这个问题。那么您应该有一个BaseControlType,其中包含可以强制转换到的属性“SelectedItemName”,您可以在
SomeMethod(…)
调用中使用该属性。请参阅我的编辑。这也是我想要建议的,界面:)我无法控制用户控件,但我同意您的看法,这是正确的方法。@edocetirwi无法控制用户控件,反射可能是达到这一目的的唯一方法。如果将u1
定义为typeUserControl
,那么将u1=u1定义为ControlType
有什么意义呢?