简体   繁体   中英

Add Item into a generic List in C#

I tried to insert an object into a generic BindingList. But if I try to add a specific object the compiler says: "Argument type ... is not assignable to parameter type"

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

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

Please help me

You cannot have objects of two different types that does not have a common anscestor in a strongly typed list. That is: In your case you will need to different collections unless your two (or more) classes have a common base class.

Try creating overloads instead, like this

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

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

Use it like this

JoinLeaveItem(userInformationCollection)
JoinLeaveItem(groupInformationCollection)

Note: I've inlined the tmp variable.

From what you've described in your comments do you want to do something like this....

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

EDIT If you want to add extra Tests to limit to only the items you specify you could add a big test at the beginning

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); 
        } 
    } 

Alternatively you can make a more generic solution via use of an interface.

Define an interface

public interface ILeaveItem { }

Make UserInformation and GroupInformation inherit from it and then use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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