如题 如何获取这个List里面的值。前提是我不知道这个List里面是什么类型我把一个List<MyEntity> 作为一个Object对象传到一个方法里了,那这个方法怎么获取List里面的值呢?
List<MyEntity> a = new List<MyEntity>();
a.Add(obj);
MyFun(a);public void MyFun(Object obj){
//如何获取这个List里面的值。前提是我不知道这个List里面是什么类型
}

解决方案 »

  1.   

    MyFun中的参数为什么要用Object来装箱呢?可以直接
    public void MyFun(List <MyEntity> obj){
    //如何获取这个List里面的值。前提是我不知道这个List里面是什么类型
    },如果你一定要装箱的话,看看能不能进行数据转换了:
    public void MyFun(Object obj){
    //如何获取这个List里面的值。前提是我不知道这个List里面是什么类型
    List<MyEntity> listObj=(List<MyEntity>)obj;
    }
      

  2.   


    恩,程序的需要,所以要装箱,至于转换,是转换不了的,因为我不知道具体这个类型是什么类型。我很想把这个Object类型转换成List<Object>,这样,我就可以用反射把他的属性值都取出来,但我实在不知道怎么转换。或者说用别的方法?
      

  3.   

     List <MyEntity> listObj=(List <MyEntity>)obj; 获取list每个项的值需要转换,类型取决于赋值时实际类型
      

  4.   

    public void MyFun<T>(List<T> obj)要用泛型就用到底,别搞得不伦不类的就没有意义了...
      

  5.   

    另外不要动不动就拿“装箱”来唬人...List<T>是引用类型,这里根本没有装箱操作...
      

  6.   


    不好意思,其实我具体的东西没写太多,害怕把大家绕进去了。是这样的我用一个方法,去获取这个对象里面的属性值public bool AuditDeleteObject(Object obj, String userName)
            {
                PropertyInfo[] pis = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);//获得对象的所有public属性
                Dictionary<string, PropertyInfo> DCPropertyInfo = new Dictionary<string, PropertyInfo>();
                foreach (PropertyInfo pi in pis)
                {
                     
                    if (pi.PropertyType.Name.ToString()=="List`1")
                    {//如果这个对象的属性是个List集合
                        if (pi.GetValue(obj, null) != null)
                        {
                            AuditDeleteObject(pi.GetValue(obj, null), userName);
                            //本来想递归调用去继续解析这个属性对象,但传过去的list,就不会了
                        }
                    }
                    else
                    {
                        DCPropertyInfo.Add(pi.Name.ToUpper(), pi);
                    }            }
                return true;
            }
      

  7.   

    反射。实例代码
    // Code for building SimpleType.dll.
    using System;namespace Simple_Type
    {
        public class MySimpleClass
        {
            public void MyMethod(string str, int i)
            {
                Console.WriteLine("MyMethod parameters: {0}, {1}", str, i);
            }        public void MyMethod(string str, int i, int j)
            {
                Console.WriteLine("MyMethod parameters: {0}, {1}, {2}", 
                    str, i, j);
            }
        }
    }
    using System;
    using System.Reflection;
    using System.Globalization;
    using Simple_Type;
    namespace Custom_Binder
    {
        class MyMainClass
        {
            static void Main()
            {
                // Get the type of MySimpleClass.
                Type myType = typeof(MySimpleClass);            // Get an instance of MySimpleClass.
                MySimpleClass myInstance = new MySimpleClass();
                MyCustomBinder myCustomBinder = new MyCustomBinder();            // Get the method information for the particular overload 
                // being sought.
                MethodInfo myMethod = myType.GetMethod("MyMethod", 
                    BindingFlags.Public | BindingFlags.Instance,
                    myCustomBinder, new Type[] {typeof(string), 
                        typeof(int)}, null);
                Console.WriteLine(myMethod.ToString());
                
                // Invoke the overload.
                myType.InvokeMember("MyMethod", BindingFlags.InvokeMethod, 
                    myCustomBinder, myInstance, 
                        new Object[] {"Testing...", (int)32});
            }
        }    //****************************************************
        //  A simple custom binder that provides no
        //  argument type conversion.
        //****************************************************
        class MyCustomBinder : Binder
        {
            public override MethodBase BindToMethod(
                BindingFlags bindingAttr,
                MethodBase[] match,
                ref object[] args,
                ParameterModifier[] modifiers,
                CultureInfo culture,
                string[] names,
                out object state)
            {
                if(match == null)
                    throw new ArgumentNullException("match");
                // Arguments are not being reordered.
                state = null;
                // Find a parameter match and return the first method with
                // parameters that match the request.
                foreach(MethodBase mb in match)
                {
                    ParameterInfo[] parameters = mb.GetParameters();                if(ParametersMatch(parameters, args))
                        return mb;
                }
                return null;
            }        public override FieldInfo BindToField(BindingFlags bindingAttr, 
                FieldInfo[] match, object value, CultureInfo culture)
            {
                if(match == null)
                    throw new ArgumentNullException("match");
                foreach(FieldInfo fi in match)
                {
                    if(fi.GetType() == value.GetType())
                        return fi;
                }
                return null;
            }        public override MethodBase SelectMethod(
                BindingFlags bindingAttr,
                MethodBase[] match,
                Type[] types,
                ParameterModifier[] modifiers)
            {
                if(match == null)
                    throw new ArgumentNullException("match");            // Find a parameter match and return the first method with
                // parameters that match the request.
                foreach(MethodBase mb in match)
                {
                    ParameterInfo[] parameters = mb.GetParameters();
                    if(ParametersMatch(parameters, types))
                        return mb;
                }            return null;
            }        public override PropertyInfo SelectProperty(
                BindingFlags bindingAttr,
                PropertyInfo[] match,
                Type returnType,
                Type[] indexes,
                ParameterModifier[] modifiers)
            {
                if(match == null)
                    throw new ArgumentNullException("match");
                foreach(PropertyInfo pi in match)
                {
                    if(pi.GetType() == returnType && 
                        ParametersMatch(pi.GetIndexParameters(), indexes))
                        return pi;
                }
                return null;
            }        public override object ChangeType(
                object value,
                Type myChangeType,
                CultureInfo culture)
            {
                try
                {
                    object newType;
                    newType = Convert.ChangeType(value, myChangeType);
                    return newType;
                }
                // Throw an InvalidCastException if the conversion cannot
                // be done by the Convert.ChangeType method.
                catch(InvalidCastException)
                {
                    return null;
                }
            }        public override void ReorderArgumentArray(ref object[] args, 
                object state)
            {
                // No operation is needed here because BindToMethod does not
                // reorder the args array. The most common implementation
                // of this method is shown below.
                
                // ((BinderState)state).args.CopyTo(args, 0);
            }        // Returns true only if the type of each object in a matches
            // the type of each corresponding object in b.
            private bool ParametersMatch(ParameterInfo[] a, object[] b)
            {
                if(a.Length != b.Length)
                    return false;
                for(int i = 0; i < a.Length; i++)
                {
                    if(a[i].ParameterType != b[i].GetType())
                        return false;
                }
                return true;
            }        // Returns true only if the type of each object in a matches
            // the type of each corresponding entry in b.
            private bool ParametersMatch(ParameterInfo[] a, Type[] b)
            {
                if(a.Length != b.Length)
                    return false;
                for(int i = 0; i < a.Length; i++)
                {
                    if(a[i].ParameterType != b[i])
                        return false;
                }
                return true;
            }
        }
    }
      

  8.   


    问题是,我不知道List 里面是什么类型的东西,所以我不能这样来转换,如果知道就简单了  :(
      

  9.   

    static void Main()
            {
                List<int> list = new List<int>();
                list.Add(1);            Object o = list;            List<int> anotherList = (List<int>)o;
                for (int i = 0; i < anotherList.Count; i++)
                {
                    Console.WriteLine(anotherList[i]);
                }            Console.ReadLine();
            }
    我发现这两者之间是可以进行转换的!
      

  10.   

    不知道就用object代替吧,浪费资源了!
      

  11.   

    是的,可以转换,但是前提是你知道List里面是Int,但是如果不知道,
    用List<Object> lobj =Obj as List<Object>; 
    lobj对象始终为null
      

  12.   

    泛型不太好操作,一个比较笨的写法
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Reflection;namespace WindowsApplication276
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();            List<String> a = new List<String>();
                a.Add("A");
                MyFun(a);
            }        public void MyFun(Object obj)
            {
                Type T = obj.GetType();            if (T.GetInterface("IList") != null && T.IsGenericType)
                {
                    String FullTypeString = T.FullName;
                    FullTypeString = FullTypeString.Remove(0, FullTypeString.IndexOf("[[") + 2);                String SubItemTypeString = FullTypeString.Substring(0, FullTypeString.IndexOf(','));                if (Type.GetType(SubItemTypeString) == typeof(String))
                    {
                        List<String> L = (List<String>)obj;
                        MessageBox.Show(L[0]);
                    }
                }
            }
        }
    }
      

  13.   

    欧拉~~问题自己解决了
    不过还是谢谢以上回答的朋友们,给了我很多提示
    用这个方法可以解决掉,转换为数组。以下是关键代码if (pi.PropertyType.IsGenericType && pi.PropertyType.GetInterface("IList")!=null)
                        {
                            Object ListO = pi.GetValue(obj, null);
                            if (ListO != null)
                            {
                                MethodInfo method = ListO.GetType().GetMethod("ToArray");
                                AuditDeleteObjects(method.Invoke(ListO, null), userName);
                            }
                        }如果是List 就调用它自己的ToArray方法public bool AuditDeleteObjects(Object obj, String userName)
            {
                Object[] objs;
                if (obj.GetType().IsArray && obj.GetType().BaseType.FullName == "System.Array")
                {
                    objs = obj as Object[];
                }
                else {
                    objs =new Object[] {obj};
                }
    .......
    }
      

  14.   

    List<MyEntity> a = new List<MyEntity>();
    a.Add(obj);
    MyFun(a);public void MyFun<T>(List<T> t){
    //如何获取这个List里面的值。前提是我不知道这个List里面是什么类型
    t.foreach(x=>{
    var yy=x.xxx...
    ...
    });
    }