繁体   English   中英

将项目添加到C#中的通用列表中

[英]Add Item into a generic List in C#

我试图将对象插入通用的BindingList中。 但是,如果我尝试添加特定的对象,则编译器会说: “参数类型...无法分配给参数类型”

private void JoinLeaveItem<T>(BindingList<T> collection)
    {

        if (collection.GetType().GetGenericArguments()[0] == typeof(UserInformation))
        {
            var tmp = new UserInformation();
            collection.Add(tmp);
        }
    }

请帮我

在强类型列表中,不能有两种没有公共祖先的不同类型的对象。 也就是说:在您的情况下,除非两个(或更多)类具有相同的基类,否则您将需要不同的集合。

尝试像这样创建重载

private void JoinLeaveItem(BindingList<UserInformation> collection)
{
    collection.Add(new UserInformation());
}

private void JoinLeaveItem(BindingList<GroupInformation> collection)
{
    collection.Add(new GroupInformation());
}

这样使用

JoinLeaveItem(userInformationCollection)
JoinLeaveItem(groupInformationCollection)

注意:我已经内联了tmp变量。

根据您在评论中描述的内容,您想要执行以下操作...。

private void JoinLeaveItem<T>(BindingList<T> collection)  where T: new()
    { 
            var tmp = new T(); 
            collection.Add(tmp); 
    } 

编辑如果您想添加额外的测试以仅限制您指定的项目,则可以在开始时添加一个大测试

private void JoinLeaveItem<T>(BindingList<T> collection)  where T: new()
    { 
        if (typeof(T) == typeof(UserInformation) || typeof(T) == typeof(GroupInformation) 
            var tmp = new T(); 
            collection.Add(tmp); 
        } 
    } 

另外,您可以通过使用接口来制定更通用的解决方案。

定义接口

public interface ILeaveItem { }

使UserInformation和GroupInformation从其继承,然后使用

private void JoinLeaveItem<T>(BindingList<T> collection)  where T: ILeaveItem, new()
    { 
            var tmp = new T(); 
            collection.Add(tmp); 
    } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM