English 中文(简体)
用户控制开关
原标题:UserControl switch

There are two different UserControls which share some common Properties. What I d like to do is to switch between these two based on an external flag.

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);

由于用户控制没有名为“ 选中项目” 的属性, 代码不会丢弃错误 。

我目前所做的是,我添加了一个用户控制扩展方法, 使用反射获得“ 选中项目名称 ”, 我通过调用 u1. 选中项目名称( ) 而不是 u1. 选中项目 来获得此值 ;

我的问题是,在不使用扩展/也许正确的方式的情况下,什么是解决问题的简单方法。 请注意,我不想在声明(a,b)中重复SomeMethod (a,b) 。

最佳回答

我的建议是让这两个 < code> User Control 类执行共享界面或来自共享基级。 然后,你可以与基级或界面相对照,而不必担心旗帜/开关。

IYourUserControl u1, u2;

SomeMethod(u1, u2);

如果能做到这一点,将可开展工作,但有些方法被界定为:

void SomeMethod(IYourUserControl one, IYourUserControl two) { // ...
问题回答

试试这支队伍:

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);
}

或者,如果你创建一个 BasicControlType 包含 SectrictemName ControlType1 ControlType2 , 包含 SectricType1 untryType2 , 您可以这样做:

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);




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...