C# 如何将结构体作为参数传递给通过反射调用的 .DLL 方法?

问题描述 投票:0回答:1

我有一个通过反射动态调用的DLL, 当我尝试发送结构作为参数时,它会生成以下错误: “System.ArgumentException:‘MRaport’类型的对象无法转换为‘MRaport’类型。” 我该如何解决这个问题?

public struct MRaport
    {
        public int rapId;
        public string rapName;
        public string Level;
    }

private void CreateRap()
   {
       Assembly assembly = Assembly.LoadFrom(@"path\RapLibrary.dll");
       Type myLibraryType = assembly.GetType("XReport");
       object myLibraryInstance = Activator.CreateInstance(myLibraryType);

       bool x = true;
       MRaport mr = new MRaport { rapId = 1, rapName = "MxFolder", Level = "Red" };
       MethodInfo methodInfo = myLibraryType.GetMethod("fillRaport");
       object[] parameters = new object[] { x, mr };

       try
       {
          string result = (string)methodInfo.Invoke(myLibraryInstance, parameters);
          MessageBox.Show(result);
       }
       catch (Exception ex)
       {
          MessageBox.Show(ex.Message);
       }
   }

类库(DLL):

public struct MRaport
    {
        public int rapId;
        public string rapName;
        public string Level;
    }

    public class XReport
    {
        public string fillRaport(bool x, MRaport mr)
        {
            if (x)
            {
               return mr.rapName;
            }
            else
            {
               return mr.Level;
            }
        }
    }
c# dll reflection
1个回答
0
投票

问题是您的

MRaport
不是类库中的
MRaport
,因此不是它所期望的。虽然肉眼看起来有点像,但还是不一样。

因此,您需要做的是首先从类库创建类型(例如,使用

Activator.CreateInstance

),填写其字段(通过反射类型或使用 
dynamic
),然后将其传递到函数调用中就像你现在一样。

© www.soinside.com 2019 - 2024. All rights reserved.