簡體   English   中英

通過反射實例化泛型類型

[英]Instantiate generic type by reflection

假設我已經通過Activator.CreateInstance實例化了泛型類型。 如果我在編譯時沒有T(但是我將其作為Type實例),是否可以將其轉換為ISomeInterface?

這是一個示例:

public static IPropertyAssertions<T> ShouldHave<T>(this T subject)
{
    var implementedInterfaces = subject.GetType().GetInterfaces();
    foreach (var interfaceType in implementedInterfaces)
    {
        if (!interfaceType.IsGenericType)
            continue;

        var genericType = interfaceType.GetGenericTypeDefinition();
        if (genericType == typeof(IEnumerable<>))
        {
            var genericTypeArg = genericType.GetGenericArguments()[0];

            var collectionPropertyAssertionsType = typeof (CollectionPropertyAssertions<>);

            Type makeme = collectionPropertyAssertionsType.MakeGenericType(genericTypeArg);

            return (IPropertyAssertions<ToDo: specify argument type here>) Activator.CreateInstance(makeme);
        }
    }

    ...
}

所以我有可以在IEnumerable<T>上調用的擴展方法。 在這種情況下,我想返回的不是CollectionPropertyAssertions<IEnumerable<T>>而是返回CollectionPropertyAssertions<T> ,其中T是枚舉元素的類型。

您將無法投射到它,沒有-你要投哪個是在編譯時已知的類型......一半的一點是,然后可以使用該類型的特定成員。

您可能需要考慮以下幾種情況:

  • 如果要調用需要ISomeInterface<T>作為參數的通用方法,則可以通過反射或使用動態類型進行調用
  • 如果您想調用無論如何都不依賴T成員,則可能要考慮創建一個ISomeInterface<T>擴展的非通用基本接口-然后可以將其ISomeInterface<T>轉換為非通用接口。

如果這不能滿足您的要求,請提供更多詳細信息。

編輯:在這種情況下,您確實知道T因為您使用的是通用方法-因此,您只需要IPropertyAssertions<T>轉換為IPropertyAssertions<T>

暫無
暫無

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

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