开发者

Is there a way to overload Items.Add procedure in inherited class from DropDownList?

开发者 https://www.devze.com 2023-01-07 09:31 出处:网络
I have my own custom class which inherits from DropDownList. Is there a way to override Items.Add procedure? H开发者_运维技巧ow?Is there a specific reason why you want to inherit from this class, as i

I have my own custom class which inherits from DropDownList. Is there a way to override Items.Add procedure? H开发者_运维技巧ow?


Is there a specific reason why you want to inherit from this class, as in are you providing this class to an interface? If the answer is no then you really should use composition over inheritance; then your problem wouldn't exist.

see Prefer composition over inheritance?


You can't override the default Add functionality -- ListItemCollection is sealed -- but you could write an extension method that extends the ListItemCollection class. Here's an example:

namespace Truthseeker.Extensions
{
    using System.Web.UI.WebControls;

    public static class ListItemCollectionExtensions
    {
        public static void Add(
            this ListItemCollection collection, 
            ListItem item, 
            string extraParameter)
        {
            if (extraParameter.Contains("Add"))
                collection.Add(item);
        }
    }
}

You can then write something like:

DropDownList ddl = new DropDownList();
ddl.Items.Add(new ListItem("text", "value"), "Add");
0

精彩评论

暂无评论...
验证码 换一张
取 消