protected void FillDataReaderToT<T>(ref T tableStruct, SqlDataReader thisReader)
        {
            //FieldInfo[] fieldInfos = typeof(T).GetFields();
            thisReader.Read();
            for (int i = 0; i < thisReader.FieldCount ; i++)
            {
                FieldInfo fieldInfo = tableStruct.GetType().GetField(thisReader.GetName(i).ToLower());
                if(fieldInfo!=null)
                    fieldInfo.SetValue(tableStruct, thisReader.GetValue(i));
            }
                        
        }T tableStruct:是传入的一个struct,已经初始化。
为什么在执行fieldInfo.SetValue(tableStruct, thisReader.GetValue(i));
时,tableStruct始终不能获得值

解决方案 »

  1.   

    有值的呀,不知道你是怎么穿那个struct的。看看我下面的代码或许有帮助。
    using System;
    using System.Collections.Generic;
    using System.Text;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Test obj = new Test();
                TableStruct Tstr = new TableStruct();
                obj.Print<TableStruct>(ref Tstr);            Console.Read();
            }
        }    public struct TableStruct
        {
            public string Name;
            public int Age;        public override string ToString()
            {
                return "sss";
            }
        }    public class Test
        {
            public void Print<T>(ref T pp)
            {            Console.WriteLine(pp.ToString());
            }
        }
    }
      

  2.   

    那个tableStruct是这样传进去的。
                    stCompany newCompany = new stCompany ();
                    FillDataReaderToT(ref newCompany,thisReader);
    应该不会有什么问提啊
      

  3.   

    问题是出在 你传进去的T 是个 struct
    如果是个class 就没问题了当你做 fieldInfo.SetValue(tableStruct, thisReader.GetValue(i)); 的时候
    SetValue 的参数是 object
    就是说 tableStruct 这个struct 被box 到一个object 里面 也就是说它被从stack 复制到heap 上面 而且这个object 是另外一个对象 而不是原来的tableStruct 了
    而SetValue 所set 的也是这个复制品 所以当你返回到tableStruct 的时候 它的值是不变的
      

  4.   

    protected void FillDataReaderToT<T>(ref T tableStruct, SqlDataReader thisReader)
            {
                //加这行 把它先box 起来
                object obj = (object)tableStruct;
                thisReader.Read();
                for (int i = 0; i < thisReader.FieldCount; i++)
                {
                    FieldInfo fieldInfo = tableStruct.GetType().GetField(thisReader.GetName(i));
                    if (fieldInfo != null)
                    {                    object val = thisReader.GetValue(i);
                        //用obj 来set value
                        fieldInfo.SetValue(obj, val);
                    }
                }
                //加这行把obj unbox
                tableStruct = (T)obj;
            }