1

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

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

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

请帮我

4

2 回答 2

1

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

尝试创建重载,就像这样

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

于 2012-05-04T08:58:39.803 回答
0

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

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); 
    } 
于 2012-05-04T09:16:31.607 回答