public interface IBase { }
public class Base<T> : IBase
{
public static string GenericName { get { return typeof( T ).Name; } }
}
public class A : Base<int> { }
public class B : Base<float> { }
public class C : Base<string> { }
class Program
{
static void Main( string[] args )
{
Type findType = typeof( IBase );
Type[] types = ( from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
from assemblyType in domainAssembly.GetTypes()
where findType.IsAssignableFrom( assemblyType )
select assemblyType ).ToArray();
// i = 2 is class A
for( int i = 2; i < types.Length; i++ )
{
Type type = types[i];
PropertyInfo propertyInfo = type.GetProperty( "GenericName", BindingFlags.Public | BindingFlags.Static );
if( null != propertyInfo ) // propertyInfo is NULL!
{
string getType = (string)propertyInfo.GetValue( null, null );
}
}
}
}
我们已经实现了GetType of Base来检查A,B,C的类型,但我们无法调用它。 为什么GetProperty的结果为null? 这些问题有没有解决方案?
答案 0 :(得分:1)
static void Main(string[] args)
{
Type findType = typeof(IBase);
Type[] types = (from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
from assemblyType in domainAssembly.GetTypes()
where findType.IsAssignableFrom(assemblyType)
select assemblyType).ToArray();
for (int i = 0; i < types.Length; i++)
{
PropertyInfo propertyInfo = types[i].GetProperty("GetType", BindingFlags.Static| BindingFlags.FlattenHierarchy| BindingFlags.Public);
if (null != propertyInfo) // propertyInfo is NULL!
{
string getType = (string)propertyInfo.GetValue(null, null);
}
}
}