无法将&#39; <t> d__14`1 [System.Object]转换为IEnumerable`1 [System.Int32]&#39;

时间:2017-01-12 14:59:52

标签: c# reflection ienumerable yield system.reflection

我尝试创建 IEnumerable 的生成器来设置 School.Foundation

这是我此刻试图填充的类型:

public class School
{
    public IEnumerable<int> Foundation;
}
到目前为止,这是我的发电机:

public static IEnumerable<T> GetEnumerable <T>(Func<T> f)
    {
        while(true)
        {
            yield return f();
        }
    }

所以我正在做的是以下反思:

Dictionary<string, Func<object>> funcMembers;

public static object Generator(String name, Type t)
{
    Func<object> func;
    if (funcMembers.TryGetValue(name, out func))
    {
         if (t.Name.StartsWith("IEnumerable"))
             return GetEnumerable(func);
    }
}

我做了以下测试以检查它是否完全正常运行:

    [TestMethod]
    public void Test_generator()
    {   
        private Dictionary<string, Func<object>> funcMembers = new Dictionary<string, Func<object>>();

        //adding the Field "Foundation" generator on the dictionary
        funcMembers.Add("Foundation", () => {return 4;}); 

        School s = new School();

        // calling my Generator that should return IEnumerable<int>
        s.Foundation = Generator(
                         "Foundation",
                          typeof(School).GetField("Foundation").

        Assert.IsNotNull(s.Foundation);
    }

当我在线时出现以下错误:

s.Foundation = Generator(
                     "Foundation",
                      typeof(School).GetField("Foundation").

错误如下:

> Unable to cast object of type '<GetEnumerable>d__14`1[System.Object]'
> to type 'System.Collections.Generic.IEnumerable`1[System.Int32]'.

1 个答案:

答案 0 :(得分:1)

您的funcMembers包含此内容:

funcMembers.Add("Foundation", () => {return 4;}); 

右侧是匿名委托,无参数,返回常量4。它被隐含地键入Func<object> soit可以添加到字典中。作为所有代理,编译器将其编译为一个类,但由于它没有名称,因此特殊名称为&#34; d__14`1 [System.Object]&#34;是自动生成的。

然后,似乎GeneratorGetEnumerable方法直接返回此委托对象,而不是调用它并获取4的值并将其包装到IEnumerable中。

然后将从GeneratorGetEnumerable返回的该委托分配给s.Foundation,这会导致您注意到此错误(因为委托的匿名类显然没有实现IEnumerable)。

我敢打赌,你可以通过踩着调试器来看到所有这些。为了更好的观点,写下来:

   var tmp = Generator(
                     "Foundation",
                      typeof(School).GetField("Foundation")...
   s.Foundation = tmp;

并观察TMP中的值,然后,诊断出是什么(例如,通过踏入Generator并查看那里发生的事情)并修复它。

旁注:这就是你粘贴的这些代码片段。我无法告诉您有关您的问题的更多信息,因为您提供的代码包含严重错误(即Generator - 并非所有代码路径都返回值),某些行不完整(其中的结尾是typeof(School).GetField("Foundation").?)等等。

在这种情况下,请尝试提供实际编译的minimal complete example