2012-07-09 105 views
0

我有点新的反思,所以原谅我,如果这是一个更基本的问题我正在编写一个程序在C#中,并试图编写一个通用的空或空检查方法 到目前为止代码读取,使用反射投出一个对象

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

现在显然是一个列表,我需要一种方法来弄清楚它是什么类型的泛型列表的,所以我想使用反射来弄明白,再与该反射投正是这种可能

谢谢

+0

不管你做什么,移动测试空顶部的启发。你现在有各种空解除引用。 – 2012-07-09 23:57:30

+0

这些对象来自哪里,你失去了所有类型的信息? – bmm6o 2012-07-10 00:00:27

+0

任何地方我真的不在乎它只是一个通用的方法,我可以用我的程序来快速找出这个对象,即时处理是空的还是空的 - 而不是写出我使用的每个特定项目的支票 – 2012-07-10 00:02:36

回答

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(); 
    } 
} 
+0

不能因为生病使用这个标准对象列表alsosuch列表 2012-07-10 00:47:23

+0

@AlexKrups:对不起,不知道我是否按照问题所在。 '列表'对象可以通过这个传入。 – 2012-07-10 00:52:21

+0

列表实现IEnumerable ,所以它将与此代码一起工作,就像任何其他实现该接口的类一样。在这种情况下,你真的需要让类型系统为你工作,而不是用反射来覆盖所有的基础。不要重新发明方形轮。 – FishBasketGordo 2012-07-10 01:56:17

3

如果您使用.NET 4,你可以采取IEnumerable<out T>的新支持的协方差考虑,并作为这样写:

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

我会然而,提出一个更好的名称,如一个由string.IsNullOrEmpty

+0

这适用于引用类型,但不适用于值类型。 – Siege 2012-07-10 00:41:07