2

IList または List をプロパティとして持っているとします。リストまたは IList であることがどのようにわかりますか? 試行錯誤に頼らずにこれを行うことはできますか?

型の名前は List`1 のようなものになりがちです。文字列のハックを検討するのは合理的ですか?

class Program {

    public class Class1 {
        public int a { get; set; }

        public IList<int> list { get; set; }


        public List<int> concreteList { get; set; }
    }

    static void Main(string[] args)
    {
        Test1();
        Test2();
    }

    private static void Test1()
    {
        var t = typeof (Class1);
        var p = t.GetProperty("list");

        if (p.PropertyType.IsInterface && p.PropertyType.IsGenericType)
        {
            var ps = p.PropertyType.GetGenericArguments();
            var underlying = p.PropertyType.GetInterface("IList");

            var b = underlying == typeof (IList<>);

        }
    }

    private static void Test2() {
        var t = typeof(Class1);
        var p = t.GetProperty("concreteList");

        if (!p.PropertyType.IsInterface && p.PropertyType.IsGenericType) {
            var ps = p.PropertyType.GetGenericArguments();

            var underlying3 = p.PropertyType.GetGenericTypeDefinition();

            var b = underlying3 == typeof (List<>);
        }
    }
}
4

2 に答える 2

5

プロパティ値を取得できれば、その型のテストは非常に簡単です (Guffa の回答を参照)。ただし、プロパティを呼び出さずにそれを見つけたい場合、コードはほとんどそこにあります-たとえば、

var t = p.PropertyType;
if (t.IsGenericType && !t.IsGenericTypeDefinition && !t.IsInterface && !t.IsValueType) 
{
   // we are dealing with closed generic classes 
   var typeToTest = typeof (List<>);
   var tToCheck = t.GetGenericTypeDefinition();
   while (tToCheck != typeof(object)) 
   {
      if (tToCheck == typeToTest) 
      {
         // the given type is indeed derived from List<T>
         break; 
      }
      tToCheck = toCheck.BaseType;
   }
}

IsGenericTypeは、タイプがジェネリックであることを示します。オープン ( List<T>) またはクローズ ( )のいずれかList<int>です。IsGenericTypeDefinitionジェネリック型がオープン型かどうかを示します。GetGenericTypeDefinitionクローズ/オープン ジェネリック型では、ジェネリック定義 (つまり、オープン ジェネリック型) が返されます。

于 2012-04-05T11:49:15.613 に答える
2

isキーワードを使用するだけです:

IList<int> list = ...get a collection from somewhere

if (list is List<int>) {
  // the IList<int> is actually a List<int>
} else {
  // the IList<int> is some other kind of collection
}
于 2012-04-05T11:32:38.577 に答える