簡體   English   中英

在運行時構建 c# 通用類型定義

[英]Build c# Generic Type definition at runtime

目前我不得不做這樣的事情來在運行時構建一個類型定義來傳遞給我的 IOC 來解決。 簡化:

Type t = Type.GetType(
"System.Collections.Generic.List`1[[ConsoleApplication2.Program+Person");

我只知道運行時的泛型類型參數。

有沒有什么可以讓我做這樣的事情(假代碼):

Type t = Type.GetTypeWithGenericTypeArguments(
    typeof(List)
    , passInType.GetType());

或者我應該堅持我的技巧, passInType.GetType()轉換為字符串,構建通用類型字符串.. 感覺很臟

MakeGenericType - 即

Type passInType = ... /// perhaps myAssembly.GetType(
        "ConsoleApplication2.Program+Person")
Type t = typeof(List<>).MakeGenericType(passInType);

一個完整的例子:

using System;
using System.Collections.Generic;
using System.Reflection;
namespace ConsoleApplication2 {
 class Program {
   class Person {}
   static void Main(){
       Assembly myAssembly = typeof(Program).Assembly;
       Type passInType = myAssembly.GetType(
           "ConsoleApplication2.Program+Person");
       Type t = typeof(List<>).MakeGenericType(passInType);
   }
 }
}

正如評論中所建議的 - 解釋一下, List<>開放的泛型類型 - 即“ List<T>沒有任何特定的T ”(對於多個泛型類型,您只需使用逗號 - 即Dictionary<,> )。 當指定T (通過代碼或通過MakeGenericType )我們得到封閉的泛型類型 - 例如, List<int>

使用MakeGenericType ,仍然會強制執行任何泛型類型約束,但只是在運行時而不是在編譯時。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM