我试图用反射复制一个功能但最终得到
CreateFormatMethod.Invoke(typDbFormatClass,null)'引发了类型'System.Reflection.TargetInvocationException'对象的异常{System.Reflection.TargetInvocationException}
内部异常显示Object reference not set to an instance of an object.
System.NullReferenceException
InnerException null
堆栈跟踪
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at AB.INIT.stringToValue(String valueInUnits, String dimension, String sourceUnit, String destinationUnit)
我试图在这里访问抽象类的静态方法。以下是完美运行的直接参考代码。
Binit.Core.Database.DbFormat format;
format = Binit.Core.Database.DbFormat.Create();
format.Dimension =
DbDoubleDimension.GetDimension((DbDimension)Enum.Parse(typeof(DbDimension), dimension));
反射代码失败并显示targetinvocationexception
Assembly CoreDatabaseAssembly = Assembly.LoadFrom(Path.Combine(APath, @"Binit.Core.Database.dll"));
Type typDbFormatClass = CoreDatabaseAssembly.GetType("Binit.Core.Database.DbFormat");
MethodInfo createFormatMethod = typDbFormatClass.GetMethod("Create", BindingFlags.Static | BindingFlags.Public, null, new Type[] { }, null);
object objDbFormat = createFormatMethod.Invoke(typDbFormatClass, null);
Type typDbDimension = CoreDatabaseAssembly.GetType("Binit.Core.Database.DbDimension");
Type typDoubleDimensClass = CoreDatabaseAssembly.GetType("Binit.Core.Database.DbDoubleDimension");
MethodInfo DbDoubleDimensionMethod = typDoubleDimensClass.GetMethod("GetDimension", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typDbDimension } , null);
object[] parametersDbDoubleDimen = new object[] { Enum.Parse(typDbDimension, dimension) };
object objDimension = DbDoubleDimensionMethod.Invoke(typDoubleDimensClass, parametersDbDoubleDimen);
我不知道如何使用反射在枚举器下面进行转换,我怀疑这是否会导致问题
(DbDimension)Enum.Parse(typeof(DbDimension), dimension)
object[] parametersDbDoubleDimen = new object[] { Enum.Parse(typDbDimension, dimension) };
dbFormat类如下所示。
namespace Binit.Core.Database
{
public abstract class DbFormat
{
protected static DbFormat m_internalDbFormat;
protected DbFormat();
public static DbFormat Create();
public static DbFormat Create(DbFormat other);
}
}
答案 0 :(得分:1)
如果我正确理解您的内容,Binit.Core.Database.DbFormat
是一个带有静态方法的嵌套类Create
如果确实如此,则执行此操作是不正确的:
createFormatMethod.Invoke(typDbFormatClass, null);
因为first parameter of Invoke should be null
是静态方法然而,我不确定为什么会导致null异常,因为通常当我看到这样的东西时,它是我的函数抛出异常(但是看起来你运行得很好所以我我不确定......)