0

我想实现一个为不同控件存储不同外观的类。起初我想使用泛型,例如:

public class Appearance<T where T : Control> { ... }

但有两个问题。首先,我想在不同控件的列表中使用这些外观,即不同的 T(在这种情况下是不可能的)。其次,每种控件类型的外观将根据它所引用的控件具有不同的属性。所以解决方案是每个控件类型的基类(最好是抽象的)和派生类:

abstract class Appearance { ... }
public class TextBoxAppearance : Appearance { ... }
public class ComboBoxAppearance : Appearance { ... }

我现在的问题是我想实现对控件类型的封装,每个类都关心,即:

public abstract class Appearance {
    public abstract void updateAppearanceOf(Control control);
}
public class TextBoxAppearance : Appearance {
    public void updateAppearanceOf([here I want to give TextBox instead of Control])
    {
        // implement update of TextBox
    }
}
public class ComboBoxAppearance : Appearance {
    public void updateAppearanceOf([here I want to give ComboBox instead of Control])
    {
        // implement update of ComboBox
    }
}

这可能吗?

4

2 回答 2

3

IEnumerable您可以使用与,类似的模式IEnumerable(T)

public interface IAppearance
{
    void Update(Control control);
}

public interface IAppearance<in TControl> : IAppearance
    where TControl : Control
{
    void Update(TControl control);
}

public class TextBoxAppearance : IAppearance<TextBox>
{
    void IAppearance.Update(Control control)
    {
        var textBox = control as TextBox;

        if(textBox == null) return;
        this.Update(textBox);
    }

    public void Update(TextBox control)
    {
        // Logic
    }
}
于 2013-11-11T17:39:11.650 回答
1

您可以使您的基类显式实现 IAppearance

public interface IAppearance
{
    void updateAppearanceOf(Control control);
}
public abstract class Appearance<T> : IAppearance where T : Control 
{
    void IAppearance.updateAppearanceOf(Control control)
    {
        if (control is T) updateAppearanceOf((T)control);
    }
    public abstract void updateAppearanceOf(T control);
}
public class TextBoxAppearance : Appearance<TextBox> {
    public override void updateAppearanceOf(TextBox control)
    {
        // implement update of TextBox
    }
}

这样所有实现抽象的类Appearance只需要担心如何处理它们的控制。

于 2013-11-11T17:48:13.947 回答