Home > Net >  How to determine a class of inheritance from another generic class above?
How to determine a class of inheritance from another generic class above?

Time:12-17

 
///
///a generic class
///

///
Public interface IClass Where TEntity: class {}

Public class Entity {}

Public class ClassEntity
{
//how to know the type of the Data, it is IClass
Public IClass Data {get; The set; }
Public string Str {get; The set; }
}

Class Program
{
The static void Main (string [] args)
{
//how to determine which properties of ClassEntity is IClass
Var entityType=typeof (ClassEntity);
Var props=entityType. The GetProperties ();
//here is my own writing, feeling a little trouble, do not know to have a simple way to
The foreach (var prop in props)
{
Var typeArgs=prop. PropertyType. GenericTypeArguments;
If (typeArgs. The Count ()==1)
{
Var args=typeArgs. Single ();
Var tableType=typeof (IClass<>) MakeGenericType (arg);
If (tableType. IsAssignableFrom (prop. PropertyType))
{
Console. WriteLine ($" PropName={prop. Name} ");
}

}
}
The Console. ReadLine ();
}
}

  •  Tags:  
  • C#
  • Related