Activator.CreateInstance - 无参数构造函数问题

时间:2017-07-20 15:52:03

标签: c# system.reflection

我正在尝试从具有EntityTypeConfiguration(Entity Framework-ism)基础的程序集中动态提取类型。在我拥有所有类型之后,我想为每个类型实例化一个对象并将其传递给构建器(DbModelBuilder)函数。

示例类:

public class LocationConfiguration : EntityTypeConfiguration<Location>
{
    public LocationConfiguration()
    {
        // some basic stuff here
    }
}

我得到的类型没问题,但我在这一行得到无参数构造函数错误:

var result = (dynamic)Activator.CreateInstance(type);

P.S。我理解在这个特定的例子中我可以使用AddFromAssembly(),但最终我想选择加载哪些配置。

编辑:

添加引发错误的行的硬编码示例:

var result = (dynamic)Activator.CreateInstance(typeof(LocationConfiguration));

编辑#2:

System.MissingMethodException occurred
  HResult=0x80131513
  Message=No parameterless constructor defined for this object.
  Source=mscorlib
  StackTrace:
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at .OnModelCreating(DbModelBuilder builder) in C:\Development\Context.cs:line 25
   at System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)

1 个答案:

答案 0 :(得分:1)

如果下面的代码是您问题的准确复制,那么答案是“因为MainWindow window = (MyApp.MainWindow)App.Current.MainWindow; window.btnSearch.Visibility = System.Windows.Visibility.Visible; 在自己的构造函数中创建EntityTypeConfiguration的实例。”

Location

在这种情况下,解决方案是创建一个EntityTypeConfiguration的子类,并为其添加一个通用约束,将其限制为using System; namespace ConsoleApp2 { class Program { static void Main(string[] args) { object thing = Activator.CreateInstance<PublicCtorClass>(); } } class PublicCtorClass : ProtectedCtorGenericClass<PublicParameterisedCtorClass> { public PublicCtorClass() { } } class ProtectedCtorGenericClass<T> { protected ProtectedCtorGenericClass() { object thing = Activator.CreateInstance(typeof(T)); } } class PublicParameterisedCtorClass { public PublicParameterisedCtorClass(object arg) { } } } 。像这样:

new()

希望这有帮助!