我想創建一個幫助器方法來爲MVC生成一個DropDown我已經涉足了表達式和反射,並且已經能夠獲取以下工作:方法的類型參數可以在方法調用中推斷爲1但不是2參數
public static DropDown GenerateDropDown<TSource, TProperty>(IEnumerable<TSource> source,
Expression<Func<TSource, TProperty>> text,
Expression<Func<TSource, object>> value,
string selectedValue = "",
string placeholder = "") where TSource : class
{
...
return new DropDown(...);
}
我可以比使用下面的代碼來生成一個下拉
DropDown.GenerateDropDown(routes, r => r.Name, r => r.Id, selectedValue, "Please Select One");
這種使用類型推斷聚集在列表(IEnumerable的)將是什麼樣的數據,並幫助我們確定應使用哪些屬性作爲文本和值,命名爲a nd Id。
注意上面的代碼有效!不過,我不喜歡使用object
作爲Expression<Func<TSource, object>> value
參數的第二個參數(它不能提供良好的智能感知)。但是,當我將其更改爲Expression<Func<TSource, TProperty>> value
(就像它上面的參數),我得到的錯誤如下:
Error CS0411 The type arguments for method 'DropDown.GenerateDropDown<TSource, TProperty>(IEnumerable<TSource>, Expression<Func<TSource, TProperty>>, Expression<Func<TSource, TProperty>>, string, string)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
這究竟是爲什麼?怎麼可能有1個工作,但當添加/更改爲2時,它會失敗?
任何幫助非常感謝,提前致謝!
「r.Name」和「r.Id」的數據類型是什麼? –
@ScottChamberlain抱歉,我無法看到數據類型的重要性,但Name是字符串,Id是小數。 – Tyler
'TProperty'不能引用2個不同的東西 - 你可以嘗試'GenerateDropDown'和'Expression >文本,表達式>值,但是它不清楚這是什麼點 –