Skip to main content
 首页 » 编程设计

c#之扩展 ASP.NET WebControls : How to effectively hide public properties

2024年01月25日26三少

我将 TextBox WebControl 扩展为一种“DateTextBox”,在代码隐藏中将其值作为属性 (DateValue) 公开:

public sealed class DateTextBox : TextBox 
{ 
    public DateTime ?DateValue 
    { 
        /* ToDateFromUserInterface() and ToUserInterfaceString() are both 
           extension methods */ 
 
        get 
        { 
            return 
            ( 
                String.IsNullOrEmpty(Text) ? 
                new DateTime?() : 
                Text.ToDateFromUserInterface() 
            ); 
        } 
 
        set 
        { 
            if (value != null) Text = ((DateTime)value).ToUserInterfaceString(); 
        } 
    } 
} 

鉴于此控件只应与日期一起使用,因此没有理由让它从其父项继承 Text 属性。

有什么方法可以隐藏它吗?除了实现 NotImplementedException 之外,像这样:

new public String Text 
{ 
    get { throw new NotImplementedException(); } 
    set { throw new NotImplementedException(); } 
} 

请您参考如下方法:

只需覆盖它并提供日期的字符串版本。任何时候从基类继承时,尝试像这样更改现有接口(interface)通常不是一个好主意……它违背了所有面向对象的实践:-P