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

时间:2012-05-04 08:56:08

标签: c#

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

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

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

请帮帮我

2 个答案:

答案 0 :(得分:1)

在强类型列表中,不能有两种不同类型的对象没有共同的anscestor。那就是:在你的情况下,你将需要不同的集合,除非你的两个(或更多)类有一个共同的基类。

尝试创建重载,例如

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变量。

答案 1 :(得分:0)

根据你在评论中描述的内容,你想做这样的事情......

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

EDIT 如果您想添加额外的测试以限制您指定的项目,您可以在开头添加一个大测试

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); 
    } 
相关问题