代码改变世界

CS控件适配使用

2007-05-06 11:44  Clingingboy  阅读(1011)  评论(0编辑  收藏  举报
       Community Server新版本又发布了,不知道大家有没有在研究,对于我来说还是狂复杂的,以前看过一段时间,想着什么时候把看的过程写下来,但总是由于各种的原因而耽搁了.现在把点点滴滴都给记录下来.因为学起来不知道从何下手,所以学到哪算到哪吧.

这次讲的是简单控件适配器的使用.

在.net2.0中,文本控件都实现了ITextControl接口,按钮系列的控件都实现了IButtonControl接口

(1)一般情况下,我们创建一个对象的时候可以用new关键字来创建

            Label testLabel = new Label();
            Button testBtn 
= new Button();

(2)另外,我们可以做一个简单的工厂来创建,代码如下

public class TextManager
{
    
public static ITextControl CreateLiteral()
    
{
        
return new Literal();
    }


    
public static ITextControl CreateLabel()
    
{
        
return new Label();
    }

}


ITextControl label = TextManager.CreateLabel();
        label.Text 
= "hello";
        Controls.Add(label 
as Label);

方便在哪里,即以后你只需要使用TextManager类来创建就可以了,不用再使用new关键字了.

现在发生了一点点的变化,不需要创建一个新的对象,我要获取一个对象,然后针对接口编程

public class TextManager
{
    
public static ITextControl CreateLiteral(Literal lit)
    
{
        
return lit;
    }


    
public static ITextControl CreateLabel(Label label)
    
{
        
return label;
    }

}

假设页面上存在一个Label控件,则

    protected void Page_Load(object sender, EventArgs e)
    
{
 
//ITextControl mylabel = Label1;
        ITextControl mylabel = TextManager.CreateLabel(Label1);
        mylabel.Text 
= "hello";
    }


接着你还可以创建一个通用的Create方法,以上的如CreateLabel这些方法说实话几乎没用.
    public static ITextControl Create(Control cntrl)
    
{
        
if (cntrl == null)
            
return null;

        ITextControl it 
= cntrl as ITextControl;
        
if (it == null)
        
{
            
if (cntrl is Literal)
                it 
= cntrl as Literal;
            
else if (cntrl is Label)
                it 
= cntrl as Label;
        }

        
return it;
    }

到了这里,我们就可以抛弃上面的两个方法了,使用Create方法.

问题来了

现在我需要扩展ITextControl接口,添加新的一些东西

    /**//// <summary>
    
/// Interface identifying a text-containing control.
    
/// </summary>

    public interface IText : ITextControl
    
{
        
bool Visible {get;set;}
        Control Control 
get;}
    }

那么我也需要扩展原来实现ITextControl的控件实现IText接口


最难的问题在这里,我们页面上用的控件都是Label和Literal,难道我们要把页面上的控件全换成CSLabel和CSLiteral?

我们只想针对接口编程,不过还是有点麻烦,你想用IText接口的话,你还是得把ITextControl换成IText,在老系统中CSLabel等新控件暂时无法发挥作用,我们需要进行适配

代码如下



来看下类图






此都是针对接口进行编程,忽略其他你不关心的功能,Manager类则充当工厂,当然有时候你并不需要这些东西,看需要吧