带反射的强制转换枚举数类型



我试图复制一个功能与反射,但最终得到

CreateFormatMethod。调用(typDbFormatClass, null)抛出了一个类型为"System.Reflection"的异常。TargetInvocationException' object {System.Reflection.TargetInvocationException}

Inner Exception显示Object reference not set to an instance of an object.系统。得到NullReferenceException

InnerException零异常堆栈

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);
}
}

如果我正确理解你在这里的内容,Binit.Core.Database.DbFormat是一个具有静态方法Create的嵌套类

如果这是真的,那么这样做是不正确的:

createFormatMethod.Invoke(typDbFormatClass, null);

因为作为静态方法,Invoke的第一个参数应该是null

然而,我不知道为什么这会导致一个空异常,因为通常当我看到这样的东西,这是我的函数抛出异常(然而它看起来像你运行它很好,所以我不确定…)

相关内容

  • 没有找到相关文章

最新更新