【发布时间】:2014-08-04 14:50:54
【问题描述】:
我在尝试使用 Activator.CreateInstance 时在我的一个解决方案中遇到了一个奇怪的错误,已将正在创建的类型上的 .ctor 参数从普通通用 T 更改为 IEnumerable。我已将足够的代码提取到控制台应用程序以进行单独测试,但它似乎工作得很好。
以下是在控制台应用程序中工作的提取代码 -
class Program
{
static void Main(string[] args)
{
Notify(new List<MyBase> { new MyBase(), new MyBase() });
}
private static void Notify<T>(IEnumerable<T> changes) where T : IMy
{
var dtoType = changes.First().GetType();
var type = typeof(MyNotification<>).MakeGenericType(dtoType);
var notification = (IMyNotification)Activator.CreateInstance(type, new object[] { changes });
}
}
public interface IMy { }
public class MyBase : IMy { }
public interface IMyNotification { }
public interface IMyNotification<T> : IMyNotification where T : IMy
{
}
public class MyNotification<T> : IMyNotification<T> where T : IMy
{
public MyNotification(IEnumerable<T> mys) { }
}
本质上,这与在我的原始解决方案中运行的代码相同。
错误是 MissingMethodException,因此找不到匹配的 .ctor。
对可能导致此问题的原因没有任何想法,查看调试器中两种解决方案的类型信息,我看不出有任何区别。所有项目都使用该解决方案进行清理和构建。
编辑
希望有人能指出我可能解决此问题的另一个方向。
谢谢
编辑
我尝试将 .ctor 更改为“对象”类型,并且通过该更改 Activator 可以创建该类型。
【问题讨论】:
-
这里有什么不使用
new MyNotification<T>(changes)的理由吗? -
你能打印/显示类型是什么吗?你确定不是
MyBase? -
@tia - 不敢相信我没有看到!原始代码不是我的,所以尝试按照它的工作方式运行。非常感谢
-
但问题是为什么是动态的?会不会有更多类型实现
IMyNotification<T>? -
@tia - 请添加您的评论作为答案,我可以接受。再次感谢!
标签: c# reflection activator