Use reflection to create C# generic objects with dynamic type specification
In C# you may need to dynamically create a generic object, such as an instance of the Task
To dynamically create a generic TaskA or TaskB object, follow these steps:
For example:
<code class="language-csharp">Type d1 = Type.GetType("namespace.TaskA`1"); Type[] typeArgs = { typeof(Item) }; var makeme = d1.MakeGenericType(typeArgs); object o = Activator.CreateInstance(makeme);</code>
If a generic class accepts multiple type parameters, be sure to include a comma when omitting the type name, for example:
<code class="language-csharp">Type type = typeof(IReadOnlyDictionary<,>); </code>
Note: The code example assumes that "namespace.TaskA1" 和
Item是已定义的类型。 实际应用中,需要根据您的具体项目替换这些占位符。 此外,错误处理(例如,处理
Type.GetType()` returns null) is critical in a production environment.
The above is the detailed content of How Can I Create Generic C# Objects with Dynamic Type Specification Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!