日期:2014-05-17  浏览次数:20899 次

out参数的问题,急!在线等
C# code

        static void Main(string[] args)
        {
            ConsoleTest.goods mode=new ConsoleTest.goods();

            testReference<ConsoleTest.goods>(out mode);
            Console.WriteLine(mode.Barcode);
            Console.ReadKey();
        }

        private static void testReference<T>(out T model) where T : new()
        {
            model = new T();
            ConsoleTest.goods good = (model as ConsoleTest.goods);
            testReference2<ConsoleTest.goods>(out good);
           
        }

        private static void testReference2<T>(out T model) where T : new()
        {
            model = new T();
            ConsoleTest.goods good = model as ConsoleTest.goods;
            good.Barcode = "111";
        }



按照我想的 应该输出“111”,为什么输出为“”

------解决方案--------------------
testReference2中重新new的model,这个和你testReference1中的ConsoleTest.goods good不是一个
------解决方案--------------------
问题出在这:

 private static void testReference<T>(out T model) where T : new()
{
model = new T();
ConsoleTest.goods good = (model as ConsoleTest.goods);
testReference2<ConsoleTest.goods>(out good);

}

你并没有将 model 往下传递。 testReference2 修改了 good 但没有修改最外面传入的 model。
good 在 testReference<T> 中只是临时变量。
C# code

private static void testReference<T>(out T model) where T : new()
{
    model = new T();
    //ConsoleTest.goods good = model as ConsoleTest.goods;
    testReference2<T>(out model);
}