我有像下面这样的课程。TestOne 方法正在运行,但 TestTwo 未运行。因为 TestTwo 有一个参数。激活器给出错误。我该如何解决这个原因?我需要一起使用 Activator.CreateInstance 和 Delegate.CreateDelegate 吗?
public class Foo
{
public Foo(string name)
{
Name = name;
}
public string Name { get; set; }
}
public class MyClass
{
public Lazy<IEnumerable<Foo>> Foos { get; set; }
}
[TestFixture]
public class Test
{
private IEnumerable<T> CreateItems<T>() where T : class
{
for (int i = 0; i < 5; i++)
{
yield return (T)Activator.CreateInstance(typeof(T), i.ToString(CultureInfo.InvariantCulture));
}
}
private IEnumerable<T> CreateItems<T>(int count) where T : class
{
for (int i = 0; i < count; i++)
{
yield return (T)Activator.CreateInstance(typeof(T), i.ToString(CultureInfo.InvariantCulture));
}
}
public IEnumerable<T> TestMethod<T>() where T : class
{
return CreateItems<T>();
}
public IEnumerable<T> TestMethod2<T>(int i) where T : class
{
return CreateItems<T>(i);
}
[Test]
public void TestOne()
{
var u = new MyClass();
var prop = u.GetType().GetProperties().First(x => x.PropertyType.IsGenericType
&& x.PropertyType.GetGenericTypeDefinition() == typeof(Lazy<>));
var enu = prop.PropertyType.GetGenericArguments()[0];
var j = enu.GetGenericArguments()[0];
var func = typeof(Func<>).MakeGenericType(enu);
var mi = this.GetType().GetMethod("TestMethod").MakeGenericMethod(j);
var factory = Delegate.CreateDelegate(func, this, mi);
var type = typeof(Lazy<>).MakeGenericType(enu);
prop.SetValue(u, Activator.CreateInstance(type, factory), null);
Debug.WriteLine("Count:" + u.Foos.Value.Count());
foreach (var foo in u.Foos.Value)
{
Debug.WriteLine(foo.Name);
}
}
[Test]
public void TestTwo()
{
var u = new MyClass();
var prop = u.GetType().GetProperties().First(x => x.PropertyType.IsGenericType
&& x.PropertyType.GetGenericTypeDefinition() == typeof(Lazy<>));
var enu = prop.PropertyType.GetGenericArguments()[0];
var j = enu.GetGenericArguments()[0];
var func = typeof(Func<,>).MakeGenericType(typeof(int), enu);
var mi = this.GetType().GetMethod("TestMethod2").MakeGenericMethod(j);
var factory = Delegate.CreateDelegate(func, this, mi);
var type = typeof(Lazy<>).MakeGenericType(enu);
// How do I send parameter to the TestMethos2 ?
// I get the error this line.
prop.SetValue(u, Activator.CreateInstance(type, factory), null);
Debug.WriteLine("Count:" + u.Foos.Value.Count());
foreach (var foo in u.Foos.Value)
{
Debug.WriteLine(foo.Name);
}
}
}