簡體   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