c# - 泛型和集合......努力实现

标签 c# generics collections

我正在尝试找出一种利用泛型的方法,这样我就可以使属性 Value 成为在创建我的集合类时初始化的实际类型(不确定这是否是正确的说法)。

我希望语法是这样的:

var list = new ListItemCollection<Guid>(parameters would go here);

我有以下类(class):

[Serializable]
public class ListItem
{
    public object Value { get; set; }
    public string Text { get; set; }
    public object DataContext { get; set; }
    public Nullable<bool> Checked { get; set; }

    public ListItem()
    {
        this.Checked = false;
    }
}

我有以下收藏:

[Serializable]
public class ListItemCollection : List<ListItem>
{
    public ListItem this[object value]
    {
        get
        {
            foreach (var child in this)
            {
                if (child.Value.Equals(value))
                    return child;
            }
            return null;
        }
    }

    public bool Contains(object value)
    {
        foreach (var child in this)
        {
            if (child.Value.Equals(value))
                return true;
        }
        return false;
    }

    public void Add(object value, string text)
    {
        this.Add(value, text, null);
    }

    public void Add(object value, string text, object dataContext)
    {
        var child = new ListItem();
        child.Value = value;
        child.Text = text;
        child.DataContext = dataContext;
        this.Add(child);
    }

    public ListItemCollection()
    {
    }

    public ListItemCollection(IEnumerable items,
        string displayMember,
        string valueMember,
        bool showEmptyItem,
        string emptyItemText,
        object emptyItemValue)
    {
        if (showEmptyItem)
        {
            this.Add(emptyItemValue, emptyItemText);
        }

        foreach (object item in items)
        {
            object text = null;
            object value = null;

            text = item.GetType().GetProperty(displayMember).GetValue(item, null);
            value = item.GetType().GetProperty(valueMember).GetValue(item, null);

            // Add the item
            this.Add(value, text.ToString(), item);
        }
    }
}

最佳答案

您可以使 ListItem 类通用:

[Serializable]
public class ListItem<T>
{
    public T Value { get; set; }
    public string Text { get; set; }
    public object DataContext { get; set; }
    public Nullable<bool> Checked { get; set; }

    public ListItem()
    {
        this.Checked = false;
    }
}

这使得该集合也具有通用性:

[Serializable]
public class ListItemCollection<T> : List<ListItem<T>>
{
    ...
}

关于c# - 泛型和集合......努力实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2607487/

相关文章:

java - 扩展接口(interface)所有实现的功能?

collections - Kotlin 中集合的构建器语法

Java Generics - 类本身的子类?

c# - SomeValue {get;} = true; 之间的区别vs SomeValue => 真;在属性中

c# - 无法创建相对 URI,因为 'uriString' 参数表示绝对 URI

Swift DynamicType 不适用于泛型函数

java - Apache CXF : jax-rs Client - GET Array of Objects

c#反序列化对象错误的JSON列表

c# - Kentico CMS v8.2 中的 Authenticate_Execute 事件覆盖

java - 通用链表删除、大小、获取方法