2016-04-03 82 views
0

我有一些調用函數的代碼。該函數使用泛型,並應添加一個新項目到綁定列表。用泛型和綁定列表添加新項目和屬性

爲了簡單起見,我分解了代碼以顯示我正在嘗試執行的操作。

調用一個函數來將項目添加到一個名爲bookToc(類型類BookToc的)的BindingList:

private CallingFunction() 
{ 
    AddFunction(bookToc, typeof(BookToc).GetProperty(nameof(BookToc.BookTocItem))) 
} 

函數使用仿製藥,應該增加一個新項的BindingList。以下是我想要的代碼做(但不工作):

public AddFunction<T>(BindingList<T> bindingList, PropertyInfo propertyName) 
{ 
    string theItem = "Hello"; 
    string theTitle = "World"; 

    //this does not work because the generic list does not know the properties available: 
    bindingList.Add(new BindingList 
    { 
     BookTocItem = theItem, 
     BookTocTitle = theTitle 
    }); 
} 

由於我使用泛型,我似乎無法添加新項目,並設置特定的屬性。我相信這是這種情況的原因是因爲它是通用的,因此不知道可用的屬性。

我需要添加一個新的行到綁定列表中,並使用泛型設置特定的屬性。這可能嗎?如果是這樣,我將非常感激代碼示例。

+0

但是你想要設置添加到BindingList的新元素的屬性的值是什麼?如果您希望AddFunction能夠向BindingList添加新元素,則還需要傳遞要在新元素中設置的每個屬性的值。這似乎不值得努力 – Steve

+0

我沒有把我的解決方案的所有代碼放在這裏,因爲它比這個簡單的例子複雜得多。在AddFunction的情況下,我希望它能夠將新行添加到BindingLIst,名爲bookToc,並將值放入BookTocItem和BookTocTitle屬性中。我無法將值傳遞給AddFunction,因爲AddFunction定義了這些值。 – Bill

+0

你打算用'propertyName'做什麼?爲什麼調用者不能設置該屬性本身? 'AddFunction'似乎做得太多了 - 它既是一種工廠方法,又將項目添加到給定的集合中。爲什麼不讓調用者添加('bookToc.Add(CreateFunction(...));')?你確定在這裏使用* generics *是有用的,因爲你需要使用* specific *屬性? –

回答

1

在函數定義中添加一個類型約束,它告訴編譯器哪些屬性可用於T.請注意下面的where子句。

public Interface IBindingListItem { 
    string BookTocItem {get; set;} 
    string BookTocTitle {get; set} 
} 

public AddFunction<T>(BindingList<T> bindingList, PropertyInfo propertyName) where T: IBindingListItem, new() 
{ 
    string theItem = "Hello"; 
    string theTitle = "World"; 

    //this does not work because the generic list does not know the properties available: 
    bindingList.Add(new T 
    { 
     BookTocItem = theItem, 
     BookTocTitle = theLinkGuid 
    }); 
    } 
+0

我還會在'T'上添加'new()'約束,並用'new T'替換'new BindingListItem'。 –

+0

BindlingListItem就是這裏的一個例子。 Howerver new T()可能不起作用,因爲不能保證T的運行時類型具有默認構造函數 –

+0

這就是'new()'約束的用途。 –