簡體   English   中英

區分類泛型類型參數和方法泛型類型參數

[英]Distinguish between a class generic type parameter and method generic type parameter

給出以下示例類:

class Foo<T>
{
  void Bar<S>(T inputT, S inputS)
  {
    // Some really magical stuff here!
  }
}

如果我反映方法Foo<>.Bar<>(...) ,並檢查參數類型,請說:

var argType1 = typeof(Foo<>).GetMethod("Bar").GetParameters()[0].ParameterType;
var argType2 = typeof(Foo<>).GetMethod("Bar").GetParameters()[1].ParameterType;

argType1argType2看起來argType2相似:

  • FullName屬性為null
  • Name屬性分別為“T”或“S”
  • IsGenericParameter是真的

參數類型信息中是否有任何內容允許我區分第一個參數是在類型級別定義的,而第二個參數是方法級別的類型參數?

我想,就像這樣:

    public static bool IsClassGeneric(Type type)
    {
        return type.IsGenericParameter && type.DeclaringMethod == null;
    }

在代碼中:

class Program
{
    static void Main(string[] args)
    {
        new Foo<int>().Bar<int>(1,1);
    }

    class Foo<T>
    {
        public void Bar<S>(T a, S b)
        {
            var argType1 = typeof(Foo<>).GetMethod("Bar").GetParameters()[0].ParameterType;
            var argType2 = typeof(Foo<>).GetMethod("Bar").GetParameters()[1].ParameterType;

            var argType1_res = Ext.IsClassGeneric(argType1);//true
            var argType2_res = Ext.IsClassGeneric(argType2);//false
        }

    }
}

暫無
暫無

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

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