use*_*188 5 c# generics reflection
class Program
{
static void Main(string[] args) {
Check(new Foo());
Check(new Bar());
}
static void Check<T>(T obj) {
// "The type T cannot be used as type parameter..."
if (typeof(T).IsSubclassOf(typeof(Entity<T>))) {
System.Console.WriteLine("obj is Entity<T>");
}
}
}
class Entity<T> where T : Entity<T>{ }
class Foo : Entity<Foo> { }
class Bar { }
Run Code Online (Sandbox Code Playgroud)
使这个东西编译的正确方法是什么?我可以Entity<T>从非泛型EntityBase类中typeof(Entity<>).MakeGenericType(typeof(T))继承子类,或者可以尝试查看它是否成功,但有没有一种方法可以不滥用try { } catch { }块或类型层次结构?
有一些方法Type就像它们可能有用一样GetGenericArguments,GetGenericParameterConstraints但是我对于如何使用它们完全无能为力......
像这样的东西应该有效。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4 {
class Program {
static void Main(string[] args) {
Check(new Foo());
Check(new Bar());
Console.ReadLine();
}
static void Check<T>(T obj) {
// "The type T cannot be used as type parameter..."
if (IsDerivedOfGenericType(typeof(T), typeof(Entity<>))) {
System.Console.WriteLine(string.Format("{0} is Entity<T>", typeof(T)));
}
}
static bool IsDerivedOfGenericType(Type type, Type genericType) {
if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)
return true;
if (type.BaseType != null) {
return IsDerivedOfGenericType(type.BaseType, genericType);
}
return false;
}
}
class Entity<T> where T : Entity<T> { }
class Foo : Entity<Foo> { }
class Bar { }
}
Run Code Online (Sandbox Code Playgroud)