簡體   English   中英

如何獲取基類的泛型類型參數?

[英]How to get base class's generic type parameter?

我有三個課程如下:

public class TestEntity { }

public class BaseClass<TEntity> { }

public class DerivedClass : BaseClass<TestEntity> { }

我已經在運行時使用反射獲取了DerivedClassSystem.Type對象。 如何使用反射獲取TestEntitySystem.Type對象?

謝謝。

我假設您的代碼只是一個示例,並且您沒有明確地知道DerivedClass

var type = GetSomeType();
var innerType = type.BaseType.GetGenericArguments()[0];

請注意,此代碼在運行時很容易失敗,您應該驗證您處理的類型是否符合您的預期:

if(type.BaseType.IsGenericType 
     && type.BaseType.GetGenericTypeDefinition() == typeof(BaseClass<>))

也可以有更深的繼承樹,因此需要一些具有上述條件的循環。

您可以使用BaseType屬性。 以下代碼對於繼承的更改是有彈性的(例如,如果在中間添加另一個類):

Type GetBaseType(Type type)
{
   while (type.BaseType != null)
   {
      type = type.BaseType;
      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(BaseClass<>))
      {
          return type.GetGenericArguments()[0];
      }
   }
   throw new InvalidOperationException("Base type was not found");
}

// to use:
GetBaseType(typeof(DerivedClass))
var derivedType = typeof(DerivedClass);
var baseClass = derivedType.BaseType;
var genericType = baseClass.GetGenericArguments()[0];

它認為這應該工作:

var firstGenericArgumentType = typeof(DerivedClass).BaseType.GetGenericArguments().FirstOrDefault();

要么

var someObject = new DerivedClass();
var firstGenericArgumentType = someObject.GetType().BaseType.GetGenericArguments().FirstOrDefault();

暫無
暫無

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

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