C#中关键字ref修饰类对象或结构体[转]

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 namespace CSharpTest
 5 {
 6     struct Dog 
 7     {
 8         public int _nFeet;
 9         public string _sound;
10         public Dog(int n, string sound)
11         {
12             _nFeet = n;
13             _sound = sound;
14         }
15         public int NFeet
16         {
17             get { return _nFeet; }
18             set { _nFeet = value; }
19         }
20         public string Sound
21         {
22             get { return _sound; }
23             set { _sound = value; }
24         }
25         public string ToString()
26         {
27             return String.Format("The dog has {0} feet, and sounds {1}.",
28                 _nFeet.ToString(), _sound);
29         }
30     }
31     class Cat
32     {
33         private int _nFeet;
34         private string _sound;
35         public Cat(int n, string sound)
36         {
37             _nFeet = n;
38             _sound = sound;
39         }
40         public int NFeet
41         {
42             get { return _nFeet; }
43             set { _nFeet = value; }
44         }
45         public string Sound
46         {
47             get { return _sound; }
48             set { _sound = value; }
49         }
50         public string ToString()
51         {
52             return String.Format("The cat has {0} feet, and sounds {1}.",
53                 _nFeet.ToString(), _sound);
54         }
55     }
56     class Program
57     {
58         static void Main(string[] args)
59         {
60             // Cat
61             Cat cat = new Cat(4, "miao~");
62             System.Console.WriteLine(cat.ToString());
63             BeatCat(cat);
64             System.Console.WriteLine(cat.ToString());
65             BeatCat2(ref cat);
66             System.Console.WriteLine(cat.ToString());
67             System.Console.WriteLine();
68             // Dog
69             Dog dog = new Dog(4, "wang!");
70             System.Console.WriteLine(dog.ToString());
71             BeatDog(dog);
72             System.Console.WriteLine(dog.ToString());
73             BeatDog2(ref dog);
74             System.Console.WriteLine(dog.ToString());
75         }
76         public static void BeatCat(Cat cat)
77         {
78             cat.NFeet = 3;
79             cat.Sound = "wang~";
80         }
81         public static void BeatCat2(ref Cat cat)
82         {
83             cat.NFeet = 2;
84             cat.Sound = "huhu~";
85         }
86         public static void BeatDog(Dog dog)
87         {
88             dog.NFeet = 3;
89             dog.Sound = "miao!";
90         }
91         public static void BeatDog2(ref Dog dog)
92         {
93             dog.NFeet = 2;
94             dog.Sound = "huhu!";
95         }
96     }
97 }
复制代码

 

posted @   MATU  阅读(1699)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示