25

次の3つのクラスがあります。

public class TestEntity { }

public class BaseClass<TEntity> { }

public class DerivedClass : BaseClass<TestEntity> { }

実行時にリフレクションを使用するSystem.Type目的は既に得ています。リフレクションを使用するオブジェクトDerivedClassを取得するにはどうすればよいですか?System.TypeTestEntity

ありがとう。

4

4 に答える 4

38

あなたのコードは単なるサンプルであり、明示的には知らないと思いますDerivedClass

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

このコードは実行時に非常に簡単に失敗する可能性があることに注意してください。処理する型が期待どおりのものであるかどうかを確認する必要があります。

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

また、より深い継承ツリーが存在する可能性があるため、上記の条件でいくつかのループが必要になります。

于 2012-08-23T08:36:10.753 に答える
5

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))
于 2012-08-23T08:44:58.050 に答える
0
var derivedType = typeof(DerivedClass);
var baseClass = derivedType.BaseType;
var genericType = baseClass.GetGenericArguments()[0];
于 2012-08-23T08:36:48.853 に答える
0

これはうまくいくはずだと思います:

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

または

var someObject = new DerivedClass();
var firstGenericArgumentType = someObject.GetType().BaseType.GetGenericArguments().FirstOrDefault();
于 2012-08-23T08:36:52.277 に答える