【问题标题】:Throw exception when get error on reflection反射出错时抛出异常
【发布时间】:2014-04-10 08:51:05
【问题描述】:

我有库和控制台程序。程序动态加载库并获取 int 数组。但是程序抛出异常。你能帮我修一下吗? 我的图书馆:

public class Class1
{
  public int [] arrayInt;
  public Class1()
  {
    arrayInt = new int[5] {1,2,3,4,5};
  }
}

我的程序:

    Assembly asm = Assembly.LoadFile(@"C:\TestLibrary.dll");
    Type Class1 = asm.GetType("TestLibrary.Class1") as Type;
    var testClass = Activator.CreateInstance(Class1);        
    MemberInfo[] List = Class1.GetMember("arrayInt");
    foreach (FieldInfo field in List)
    {
        if (field.FieldType.IsArray)
        {
            int[] array = (int[])field.GetValue(null);//throw exception here
            Console.WriteLine("Count of list. "+array.length);              
            foreach (var element in array)
                Console.WriteLine(element.ToString());
            break;
        }
    }

异常信息:

System.Reflection.TargetException:非静态字段需要一个目标。在 System.Reflection.RtFieldInfo.CheckConsistency(Object target) 在 System.Reflection.RtFieldInfo.InternalGetValue(Object obj, StackCrawlMark& stackMark) 在 System.Reflection.RtFieldInfo.GetValue(Object obj) 在 Tets.Program.Main(String[] args )

附:你能修改代码,第一个数组不取自循环吗?

【问题讨论】:

  • 如果我们知道异常是什么可能会有所帮助。
  • 哪里抛出了异常?什么样的异常?
  • 嗯...看起来您遇到了我们所说的“错误”。修复它的最佳办法是更改某些工作代码的损坏代码。一旦你完成了,你应该没问题。 (此评论/答案旨在与原始问题类似地缺乏有用信息)。
  • 试试:field.GetValue(testClass)
  • 这正是错误消息告诉您的内容! ;p

标签: c#


【解决方案1】:

在循环中的字段变量中,您有字段的定义,当您想要获取字段的值时,您应该将对象传递给GetValue 方法,因此在您的代码中您需要编写类似这样的内容

int[] array = (int[])field.GetValue(testClass);

【讨论】:

    【解决方案2】:

    由于这个 Field 实例字段(非静态),您需要将实例传递给 GetValue() 方法。

    int[] array = (int[])field.GetValue(testClass);
    

    【讨论】:

      猜你喜欢
      • 2013-05-24
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      相关资源
      最近更新 更多