Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can get <code>T</code> using strings, you do it by calling <code>GetType</code> with the string name of <code>MyClass</code> and then getting the generic arguments of the resulting type. From there you can build up the other open generic types using <code>MakeGenericType</code>. You have to work from the inside out by constructing the most nested types first. To do it automatically across differing methods would require some string parsing to get to the nested types. For the sake of comparing .Net methods against Cecil methods, @Tengiz might have a better approach.</p> <p>To run the code, update the string name of <code>MyClass</code> to have the correct namespace for your environment.</p> <pre><code>private static void Main(string[] args) { // change 'yournamespace' Type testType = Type.GetType("yournamespace.MyClass`1"); Type[] testTypeGenericArgs = testType.GetGenericArguments(); // Get T type from MyClass generic args Type tType = testTypeGenericArgs[0]; Type genericListType = Type.GetType("System.Collections.Generic.List`1"); // create type List&lt;T&gt; Type openListType = genericListType.MakeGenericType(testTypeGenericArgs[0]); Type genericTuple = Type.GetType("System.Tuple`2"); Type stringType = Type.GetType("System.String"); // create type Tuple&lt;T, string&gt; Type openTuple = genericTuple.MakeGenericType(new[] { tType, stringType }); // create type List&lt;Tuple&lt;T, string&gt;&gt; Type openListOfTuple = genericListType.MakeGenericType(openTuple); Type[] typesFromStrings = new[] { tType, openListType, openListOfTuple }; // get method parameters per example Type myClassType = typeof(MyClass&lt;&gt;); MethodInfo myMethodInfo = myClassType.GetMethod("MyMethod"); Type[] paramTypes = myMethodInfo.GetParameters().Select(pi =&gt; pi.ParameterType).ToArray(); // compare type created from strings against types // retrieved by reflection for (int i = 0; i &lt; typesFromStrings.Length; i++) { Console.WriteLine(typesFromStrings[i].Equals(paramTypes[i])); } Console.ReadLine(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload