小编Tyl*_*ler的帖子

方法调用中可以推断出方法的类型参数为1而不是2个参数

我正在尝试创建一个帮助方法来为MVC生成DropDown我已经用表达式和反射进行了一些操作,并且能够使以下工作:

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(...);
}
Run Code Online (Sandbox Code Playgroud)

我可以使用以下代码生成DropDown

DropDown.GenerateDropDown(routes, r => r.Name, r => r.Id, selectedValue, "Please Select One");
Run Code Online (Sandbox Code Playgroud)

这使用类型推断来收集列表(IEnumerable)的数据,并帮助我们确定哪些属性应分别用作Text和Value,Name和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 …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc

0
推荐指数
1
解决办法
130
查看次数

标签 统计

asp.net-mvc ×1

c# ×1