【问题标题】:Lambda with generic具有泛型的 Lambda
【发布时间】:2013-06-26 01:15:46
【问题描述】:
IDictionary<string, string> map = str.Split('|')
                                     .ToDictionary(s => s.Split('@')[0], s => s.Split('@')[1]);

上述语句有效。但我想将其更改为通用 IDictionary

public class CSVMap <TKey, TValue>
{
    public IDictionary<TKey, TValue>  func (string str)
    {
        IDictionary<TKey, TValue> map =  str.Split('|').ToDictionary (ConvertValue<TKey>(s => s.Split('@')[0]), ConvertValue<TValue>(s => s.Split('@')[1]));

    }
    public static T ConvertValue<T>(string value)
    {
        return (T)Convert.ChangeType(value, typeof(T));
    }

ConvertValue 将拆分字符串转换为TKeyTValue 的类型。

ConvertValue 部分出现这些错误:

错误 CS1660:无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型
错误 CS1660:无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型

我不确定错误的含义或如何解决此类问题。

【问题讨论】:

  • 正确的术语是“泛型”,而不是“模板”。模板是 C++ 所拥有的。
  • @JohnSaunders: .. 将其更改为 template for IDictionary

标签: c# generics


【解决方案1】:

您将 lambda 表达式而不是值传递给 ConvertValue 函数。不确定这是否符合您的预期,但至少这是正确的语法。

IDictionary<TKey, TValue> map =  str.Split('|').ToDictionary (s=>ConvertValue<TKey>(s.Split('@')[0]), s=>ConvertValue<TValue>(s.Split('@')[1]));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多