c# - 如何为各种构造函数做Activator.CreateInstance?

标签 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();
  }

我收到以下错误消息:

System.Reflection.TargetInvocationException : Ett undantagsfel har inträffat i målet för en aktivering. ----> System.TypeInitializationException : Typinitieraren för PlaynGO.Cashier.Data.CashierDC utlöste ett undantag. ----> System.NullReferenceException : Objektreferensen har inte angetts till en instans av ett objekt. vid System.RuntimeMethodHandle.InvokeConstructor(IRuntimeMethodInfo method, Object[] args, ref SignatureStruct signature, RuntimeType declaringType) vid System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) vid System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) vid System.Activator.CreateInstance(Type type, Object[] args) vid PlaynGO.Dbml.Reflexion.b_3(Type t) i Reflexion.cs: line 23 vid System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext() vid System.Collections.Generic.List1..ctor(IEnumerable1 collection) vid System.Linq.Enumerable.ToList(IEnumerable1 source) vid PlaynGO.Dbml.Reflexion.GetInstances(Assembly assembly) i Reflexion.cs: line 23 vid PlaynGO.Dbml.UnitTests.TestReflection.TestGettingTypes() i TestReflection.cs: line 21 --TypeInitializationException vid PlaynGO.Cashier.Data.CashierDC..ctor(String connection) --NullReferenceException vid PlaynGO.Cashier.Data.CashierDC..cctor()

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

    public CashierDC(string connection) :
   base(connection, mappingSource)

MappingSource是直接实例化的,是一个实例字段。我哪里出错了?我必须做什么才能使这项工作正常进行?

附言。这是 .NET 4.0

最佳答案

我认为你的错误是另外一回事。如果 Activator.CreateInstance 找不到您的构造函数,您将得到一个 MissingMethodException 而不是 TargetInvocationException。我怀疑您要实例化的实际类中还有其他问题。

关于c# - 如何为各种构造函数做Activator.CreateInstance?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4336620/

相关文章:

c# - CLR 问题。为什么 C# 中的方法重载决定 null 是一个字符串?

c# - 获取文件名子串的不同计数

c# - 在 .NET 中注册热键 - 三/四键组合

c# - 如何在嵌套 AutoMapper Project().To<>() 后执行 LINQ 操作

c# - 对值类型和引用类型使用 C# LINQ 表达式

c# - 使用 IEnumerable 和 IQueryable 作为 ObjectSet 类型时的区别

c# - MSTest期间的终结器中的NullReferenceException

c# - 如何确定文件最近一次重命名的时间?

c# - Matrix3D 入门 (Silverlight)

c# - 需要使用 C# 将文件从一台服务器移动到另一台使用 php 的服务器并进行处理?