【发布时间】:2017-05-27 17:54:25
【问题描述】:
我正在尝试创建 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]'.
【问题讨论】:
标签: c# reflection ienumerable yield system.reflection