使用反射来投射物体

Ale*_*pka 0 c# reflection

我对反思有点新意,请原谅我,如果这是一个更基本的问题我正在用c#编写一个程序,并且我试图写一个通用的Empty或null checker方法到目前为止代码读取为

 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
       }
    }
Run Code Online (Sandbox Code Playgroud)

现在很明显,对于一个列表,我需要一种方法来弄清楚它是什么类型的通用列表,所以我想使用反射来弄清楚,然后用反射投射它是可能的

谢谢

Fis*_*rdo 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();
    }
}
Run Code Online (Sandbox Code Playgroud)