扩展 ASP.NET WebControls:如何有效隐藏公共属性
我将 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(); }
}
I am extending TextBox WebControl to work as a sort of "DateTextBox" which exposes it's value as a property (DateValue
) in the code-behind:
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();
}
}
}
Given the fact that this control is only supposed to be used with dates, there's no reason for it to inherrit the Text
property from it's parrent.
Is there any way to hide it?.. Other than implementing a NotImplementedException
, like so:
new public String Text
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需覆盖它并提供日期的字符串版本即可。任何时候从基类继承时,尝试像这样更改现有接口通常都是一个坏主意......它违背了所有面向对象的实践:-P
just override it and provide a string version of the date. Any time you inherit from a base class, it's usually a bad idea to try to change the existing interface like this ... it goes against all object oriented practices :-P
您可以使用 EditorBrowsable 属性。它只会对 Intelisense 隐藏该属性,但不会破坏与基类的编译时兼容性。
不过,如果您知道该房产的名称,您仍然可以使用该房产。
PS:请阅读本文末尾的用户评论。
http://msdn.microsoft.com/en-us/库/system.componentmodel.editorbrowsableattribute.aspx
You can use EditorBrowsable attribute. It will only hide the property from Intelisense, but won't break compile time compatibility with base class.
Although you can still use the property if you know it's name.
PS: Read user comments at the end of this article.
http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx
如果您要创建一个继承另一个类的类,则父方法的所有属性仍应相关。在这种情况下,您可以返回获取日期的文本表示形式,并解析集合的文本表示形式。
If you are creating a class that inherits another class, all the properties of the parent method should still be relevant. In this case, you could return a text representation of the date for the get, and parse a text representation for the set.