5
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 { }

このことをコンパイルする適切な方法は何ですか? Entity<T>非ジェネリック クラスからサブクラス化するか、それが成功するかどうかEntityBaseを試してみることができますが、ブロックを乱用したり、型階層を破壊したりtypeof(Entity<>).MakeGenericType(typeof(T))しない方法はありますか?try { } catch { }

Typeのように便利なように見えるGetGenericArguments方法がいくつかありますが、GetGenericParameterConstraintsそれらの使用方法についてはまったくわかりません...

4

1 に答える 1

4

このようなものがうまくいくはずです。

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 { }
}
于 2013-06-12T06:40:41.460 に答える