不错的quiz

 

using System;
using System.Collections.Generic;

namespace abcd
{
    
class Program
    
{
        S s;
        
struct S
        
{
            
public int x; //public int x = 0 编译错误?解释为什么
        }


        C c 
= new C();
        
class C
        
{
            
public int x = 0;
        }
        
        
        
void print()
        
{
            Console.WriteLine(
"{0}\t{1}", s.x, c.x);
        }


        
void Foo1(S s, C c)
        
{
            s.x
++;
            c.x
++;
            print();
        }


        
void Foo2(S s, C c)
        
{
            s 
= new S();
            c 
= new C();
            print();
        }


        
void Foo3(ref S s, ref C c)
        
{
            s.x
++;
            c.x
++;
            print();
        }


        
void Foo4(ref S s, ref C c)
        
{
            s 
= new S();
            c 
= new C();
            print();
        }
       

        
void Test()
        
{
            Foo1(s, c);
            Foo2(s, c);
            Foo3(
ref s, ref c);
            Foo4(
ref s, ref c);
            
// 输出结果,解释为什么:
            
// 0    1
            
// 0    1
            
// 1    2
            
// 0    0

            List
<S> l1 = new List<S>();
            l1.Add(s);
            
//l1[0].x++; 编译错误?解释为什么

            S[] l 
= new S[1];
            l[
0= new S();
            l[
0].x++;
            
// 数组OK,解释为什么

            List
<C> l2 = new List<C>();
            l2.Add(c);
            l2[
0].x++;
            
// OK,解释为什么
        }


        
static void Main()
        
{
            
new Program().Test();
        }
       
    }

}


解释每一个为什么,并且画出对象在内存中的布局变化图!
posted @ 2008-04-03 17:35  lovecherry  阅读(2074)  评论(5编辑  收藏  举报