【问题标题】:c# Dictionary with Func<string, T> als valuesc# Dictionary with Func<string, T> als 值
【发布时间】:2014-08-29 09:02:51
【问题描述】:

我想把 T 是泛型类型的 Func 作为字典中的值。所以基本上我想做这样的事情:

 Dictionary<string, Func<MyObject, T>> _sortMappings = 
                new Dictionary<string, Func<MyObject, T>>()
    {
        { "Name", (b) => b.Name }, // name is a string            
        { "Length", (b) => b.Length }, // length is an int
        { "Date", (b) => b.Date } // a datetime object
    };

这有意义吗?这可能吗?

【问题讨论】:

  • 应该是Func&lt;T, string&gt; 吗? string 没有属性 Name,也没有 Date - 所以 lambda 甚至不符合 Func 的条件,它接受 string 并返回 T
  • 你是对的。它是自定义类的对象。已更正。
  • 你试过我的解决方案了吗?

标签: c# generics dictionary


【解决方案1】:

Func&lt;MyObject, T&gt; 不可能,您需要使用Func&lt;MyObject, object&gt;。 T 不能同时是一种以上的类型。所以你需要为stringintDateTime找到一个共同的类型,即object

【讨论】:

  • 确实,对象似乎是要走的路,但我正在寻找一种更优雅的方式,而不需要装箱/拆箱。谢谢。
【解决方案2】:

Convert.ChangeType Method这样试试

"Name", b =&gt; (T)System.Convert.ChangeType(b.Name,typeof(T))

你的功能应该是

private static T InvokeFunction<T>(Func<T> func)
    {
       Dictionary<string, Func<MyObject, T>> sortMappings =
       new Dictionary<string, Func<MyObject, T>>();
       sortMappings.Add("Name", b => (T)System.Convert.ChangeType(b.Name,typeof(T)));
       sortMappings.Add("Length", b => (T)System.Convert.ChangeType(b.Length, typeof(T)));
       sortMappings.Add("Date", b => (T)System.Convert.ChangeType(b.Date, typeof(T)));
       return func.Invoke();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    相关资源
    最近更新 更多