确定字段是否为泛型类型

Res*_*ing 1 .net c# reflection

是否可以通过反射确定一个字段是否是泛型类型?

如果有可能,怎么办呢?

我想我的问题不够明确,所以我现在正在编辑它.

编辑:

如果a将具有如以下示例中定义的类型并且DID没有Holder<T>类型的实例,但仅System.Type通过实例检索实例System.Reflection.Assembly.GetTypes并且System.Reflection.FieldInfo实例描述了字段_instance,那么如何确定_instance字段是否为泛型类型

public class Holder<T>
{
   private T _instance;
}
Run Code Online (Sandbox Code Playgroud)

tva*_*son 6

如果要了解字段本身是泛型类型,则可以使用字段的FieldInfo来检查FieldType属性的IsGenericType属性.

 var info = type.GetField("myField",BindingFlags.Private);
 if (info != null)
 {
      if (info.FieldType.IsGenericType)
      {
           Console.WriteLine( "The type of the field is generic" );
      }
 }
Run Code Online (Sandbox Code Playgroud)

如果要检查字段是否是泛型类定义中泛型的类型,那么您将要检查IsGenericParameter.

 var info = type.GetField("myField",BindingFlags.Private);
 if (info != null)
 {
      if (info.FieldType.IsGenericParameter)
      {
           Console.WriteLine( "The type of the field is the generic parameter of the class" );
      }
 }
Run Code Online (Sandbox Code Playgroud)

当然,你可以将这些结合起来.检查字段是否是通用定义类中的类型的泛型,更有问题,但仍然可以完成.您只需检查泛型类型的类型参数,以查看其中一个是否设置了IsGenericParameter.请注意,以下示例仅深度为一级; 如果你想要一些全面的东西,你需要定义一个方法并递归地使用它.

var info = type.GetField("myField",BindingFlags.Private);
if (info != null)
{
     if (info.FieldType.IsGenericType)
     {
         foreach (var subType in info.FieldType.GetGenericArguments())
         {
             if (subType.IsGenericParameter)
             {
                 Console.WriteLine( "The type of the field is generic" );
             }
         }
     }
}
Run Code Online (Sandbox Code Playgroud)