如何为各种构造函数执行Activator.CreateInstance?

mhe*_*xon 2 c#

我需要得到我的DataContext的子类,我找到了下面的函数,它位于某处,它确实找到了我的子类但我无法实例化它:(

  public static IEnumerable<T> GetSubclassesFor<T>(Assembly assembly)
  {
   return (assembly.GetTypes()
    .Where(t => t.BaseType == (typeof (T)))
    .Select(t => (T) Activator.CreateInstance(t, new object[] {"asdasd"})))
    .ToList();
  }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

System.Reflection.TargetInvocationException:ETT undantagsfel HARinträffat我MALET当EN aktivering.----> System.TypeInitializationException:TypinitierarenFÖRPlaynGO.Cashier.Data.CashierDCutlösteETT undantag.----> System.NullReferenceException:Objektreferensen har inte angetts直到en instans av ett objekt.vid System.RuntimeMethodHandle.InvokeConstructor(IRuntimeMethodInfo方法,对象[]指定参数时,REF SignatureStruct签名,RuntimeType declaringType)VID System.Reflection.RuntimeConstructorInfo.Invoke(的BindingFlags invokeAttr,粘结剂粘结剂,对象[]参数,CultureInfo的培养物)VID System.RuntimeType.CreateInstanceImpl(的BindingFlags bindingAttr,粘合剂粘合剂,对象[]指定参数时,CultureInfo的文化,对象[] activationAttributes)VID System.Activator.CreateInstance(类型类型,对象[]参数)VID PlaynGO.Dbml.Reflexion.b _3(T型)1 Reflexion.cs:线23 vid System.Linq.Enumerable.WhereSelectArrayIterator 2.MoveNext() vid System.Collections.Generic.List1..ctor(IEnumerable1 collection) vid System.Linq.Enumerable.ToList(IEnumerable1个源)VID PlaynGO.Dbml.Reflexion.GetInstances(大会组件)1 Reflexion.cs:线23个VID ​​PlaynGO.Dbml.UnitTests.TestReflection.TestGettingTypes()1 TestReflection.cs:线21个--TypeInitializationException VID PlaynGO.Cashier.Data .CashierDC..ctor(String connection) - nullReferenceException vid PlaynGO.Cashier.Data.CashierDC..cctor()

我想调用的构造函数如下:

    public CashierDC(string connection) :
   base(connection, mappingSource)
Run Code Online (Sandbox Code Playgroud)

MappingSource直接实例化,是一个实例字段.我哪里出错了?我需要做些什么来完成这项工作?

PS.这是.NET 4.0

BFr*_*ree 5

我认为你的错误是别的.如果Activator.CreateInstance找不到你的构造函数,你得到的MissingMethodException不是a TargetInvocationException.我怀疑你试图实例化的实际类中还有其他错误.