簡體   English   中英

我可以從返回類型的類型中提取 Generic 的類型嗎?

[英]Can I extract the type of Generic from a return type's type?

所以我有,說,這種類型的方法:

public ICollection<String> doSomething() { }

目前,我正在嘗試檢查方法的返回類型是否為 ICollection 類型。 但是,在 C# 中,我必須在進行檢查時傳入泛型。 所以我不能說,“方法是 ICollection”。

問題是我不想在檢查時限制泛型的類型。 在 Java 中,我可以只使用通配符,但在 C# 中不能這樣做。 我想過嘗試使用 Type.GetGenericParamterContraints() 並嘗試將它的第一個結果放在 ICollection 的通用約束中進行檢查,但這也不起作用。 有人有任何想法嗎?

isCollection(MethodInfo method){
    Type[] ret = method.ReturnType.GetGenericParametersContraint();
    Type a = ret[0];
    return method.ReturnType is ICollection<a>;
}

編輯:添加了我嘗試過的內容。

你應該能夠做到:

MethodInfo method = ... // up to you
var returnType = method.ReturnType;

var isGenericICollection = returnType == typeof(ICollection<>);

使用Type.GetGenericTypeDefinition() ,並將其結果與typeof(ICollection<>)

因此,要檢查您的方法的返回類型是否為ICollection ,您可以這樣做:

method.ReturnType.GetGenericTypeDefinition() == typeof(ICollection<>)

順便提一句。 method.ReturnType is ICollection<a>永遠不會為真,因為is檢查第一個操作數的類型是否是第二個操作數的子類型。 ReturnTypeType盡管它不是某些ICollection的子類型。

如果允許它是非通用System.Collections.ICollection (也由ICollection<T>實現),那么它只是:

typeof(System.Collections.ICollection).IsAssignableFrom(method.ReturnType)

如果您只想與通用ICollection<T>進行比較(我認為沒有理由,但您可能有自己的理由):

method.ReturnType.IsGenericType 
  && typeof(ICollection<>)
  .IsAssignableFrom(method.ReturnType.GetGenericTypeDefinition())

請注意,如果返回類型是非通用的,這將不起作用。 因此,如果有一個實現ICollection<T>但本身不是泛型的類,它將不起作用。 這意味着它不會捕獲class Foo : ICollection<string>但它捕獲class Foo<T> : ICollection<T>

不過,第一種方法可以很好地抓住兩者。

試試這個,使用MethodInfo.ReturnType確定返回類型

Use the below method, call `isCollection<string>(method)` 

public static bool isCollection<T>(MethodInfo method)
{
    return method.ReturnType.Equals(typeof(ICollection<T>));
}

嘗試這個:

class Program
{
    public ICollection<string> Foo() { return new List<string>(); } 
    public static bool TestType()
    {
        MethodInfo info = typeof(Program).GetMethod("Foo");

        return info.ReturnType.GetGenericTypeDefinition() == typeof(ICollection<>);
    }
    static void Main(string[] args)
    {
        Console.WriteLine("{0} is ICollection<> : {1}", "Foo", TestType());
    }
}

打印Foo is ICollection<> : True

暫無
暫無

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

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