0

我对反射有点陌生,所以如果这是一个更基本的问题,请原谅我,我正在用 c# 编写程序,并且正在尝试编写一个通用的 Empty 或 null 检查器方法,到目前为止代码读取为

 public static class EmptyNull
    {
       public static bool EmptyNullChecker(Object o)
       {
           try
           {
               var ob = (object[]) o;
               if (ob == null || !ob.Any())
                   return true;
           }
           catch (Exception e)// i could use genercs to figure out if this a array but                  //figured i just catch the exception
           {Console.WriteLine(e);}
           try
           {
               if (o.GetType().GetGenericTypeDefinition().Equals("System.Collections.Generic.List`1[T]"))
               //the following line is where the code goes haywire
              var ob = (List<o.GetType().GetGenericArguments()[0].ReflectedType>)o;
               if (ob == null || !ob.Any())
                   return true;
           }
           catch (Exception e)
           { Console.WriteLine(e); }
           return o == null || o.ToString().Equals("");//the only thing that can return "" after a toString() is a string that ="", if its null will return objects placeMarker
       }
    }

现在显然对于一个列表,我需要一种方法来确定它是什么类型的通用列表,所以我想使用反射来找出它,然后用反射投射它这可能吗

谢谢你

4

3 回答 3

9

如果您想要的只是一个在对象为 null 或对象为空可枚举的情况下返回 true 的方法,那么我不会为此使用反射。几个扩展方法怎么样?我认为它会更干净:

public static class Extensions
{
    public static bool IsNullOrEmpty(this object obj)
    {
        return obj == null;
    }

    public static bool IsNullOrEmpty<T>(this IEnumerable<T> obj)
    {
        return obj == null || !obj.Any();
    }
}
于 2012-07-10T00:02:12.790 回答
3

如果您使用的是 .NET 4,则可以将IEnumerable<out T>'s 对协方差的新支持考虑在内,并将其写为:

public static bool EmptyNullChecker(Object o)
{
    IEnumerable<object> asCollection = o as IEnumerable<object>;
    return o != null && asCollection != null && !asCollection.Any(); 
}

但是,我会建议一个更好的名称,例如受string.IsNullOrEmpty启发的名称

于 2012-07-10T00:04:14.457 回答
0

如何:使用反射检查和实例化泛型类型

于 2012-07-10T13:18:16.303 回答