问题描述:

I'm using a third party assembly at Runtime. The assembly exposes a single method accepting a generic list of a struct. The struct is defined within the third party assembly itself.

<thirdpartassembly>

public struct stStruct

{

public string member1;

public decimal member2;

}

public class businessType

{

public string processItems(List<stStruct> processItems)

{

//process items, then return result

}

}

</thirdpartassembly>

Given an instance of [businessType] created at runtime using reflection, I am trying to pass a list of items [listofStructItems] to the [processItems] method.

How do I define/create [listofStructItems] ?

What I tried so far:

  1. Passing a List containing stStruct items.
  2. Creating a struct that has the same definition as stStruct (cstStruct) in my code, then passing a List to the processItems method. (cannot convert list of x to list of y).

Environment:

  • third party assembly: .Net v.2
  • my assembly: anything above v.2

Any thoughts ? I would also appreciate an explanation of why none of the options above did work.

网友答案:

What I tried so far:

  1. Passing a List containing stStruct items.

Without code thats hard to say what was wrong.

  1. Creating a struct that has the same definition as stStruct (cstStruct) in my code, then passing a List to the processItems method. (cannot convert list of x to list of y).

Well thats how typesafe languages work, its a different type.

The key to solve this problem is the Type.MakeGenericType method to create a generic type with a type parameter unknown at compile time. Keep in mind that the Assembly.GetType() method requires the type name inclusive the namespace. You can inline a few of these temp variables, i created them just to be a bit more clear about the general reflection process.

var businessTypeInstance = ...;
var processItemsMethod = businessTypeInstance.GetType().GetMethod("processItems");
var stStructType = businessTypeInstance.GetType().Assembly.GetType("stStruct");
var openListType = typeof(List<>);
var closedListType = openListType.MakeGenericType(stStructType);
var listOfStruct = Activator.CreateInstance(closedListType);
var result = processItemsMethod.Invoke(businessTypeInstance, new [] { listOfStruct });


Just for broaden the mind and even that i do not recommend this, you could get the List<stStruct> type from the parameter itself:

var closedListType = processItemsMethod.GetParameters()[0].ParameterType;
相关阅读:
Top