C#基础概念二十五问

添加人:gamefriends二级(651分)   添加时间:2007-09-13    阅读次数:15079  收藏此教程

23.explicit 和 implicit 的含义?

答:

explicit 和 implicit 属于转换运算符,如用这两者可以让我们自定义的类型支持相互交换

explicti 表示显式转换,如从 A -> B 必须进行强制类型转换(B = (B)A)

implicit 表示隐式转换,如从 B -> A 只需直接赋值(A = B)

隐式转换可以让我们的代码看上去更漂亮、更简洁易懂,所以最好多使用 implicit 运算符。不过!如果对象本身在转换时会损失一些信息(如精度),那么我们只能使用 explicit 运算符,以便在编译期就能警告客户调用端

示例: 

 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4 
 5namespace Example23
 6{
 7    class Program
 8    {
 9        //本例灵感来源于大话西游经典台词“神仙?妖怪?”--主要是我实在想不出什么好例子了
10        class Immortal
11        {
12            public string name;
13            public Immortal(string Name)
14            {
15                name = Name;
16            }

17            public static implicit operator Monster(Immortal value)
18            {
19                return new Monster(value.name + ":神仙变妖怪?偷偷下凡即可。。。");
20            }

21        }

22        class Monster
23        {
24            public string name;
25            public Monster(string Name)
26            {
27                name = Name;
28            }

29            public static explicit operator Immortal(Monster value)
30            {
31                return new Immortal(value.name + ":妖怪想当神仙?再去修炼五百年!");
32            }

33        }

34        static void Main(string[] args)
35        {
36            Immortal tmpImmortal = new Immortal("紫霞仙子");
37            //隐式转换
38            Monster tmpObj1 = tmpImmortal;
39            Console.WriteLine(tmpObj1.name);
40 
41            Monster tmpMonster = new Monster("孙悟空");
42            //显式转换
43            Immortal tmpObj2 = (Immortal)tmpMonster;
44            Console.WriteLine(tmpObj2.name);
45 
46            Console.ReadLine();
47        }

48    }

49}

结果:
紫霞仙子:神仙变妖怪?偷偷下凡即可。。。
孙悟空:妖怪想当神仙?再去修炼五百年!

 
24.params 有什么用?

答:

params 关键字在方法成员的参数列表中使用,为该方法提供了参数个数可变的能力

它在只能出现一次并且不能在其后再有参数定义,之前可以

示例:

 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4 
 5namespace ConsoleApplication1
 6{
 7    class App
 8    {
 9        //第一个参数必须是整型,但后面的参数个数是可变的。
10        //而且由于定的是object数组,所有的数据类型都可以做为参数传入
11        public static void UseParams(int id, params object[] list)
12        {
13            Console.WriteLine(id);
14            for (int i = 0; i < list.Length; i++)
15            {
16                Console.WriteLine(list[i]);
17            }

18        }

19 
20        static void Main()
21        {
22            //可变参数部分传入了三个参数,都是字符串类型
23            UseParams(1, "a", "b", "c");
24            //可变参数部分传入了四个参数,分别为字符串、整数、浮点数和双精度浮点数数组
25            UseParams(2, "d", 100, 33.33, new double[] { 1.1, 2.2 });
26 
27            Console.ReadLine();
28        }

29    }

30}

结果:
1
a
b
c
2
d
100
33.33
System.Double[]

9页 第8上一页123456789下一页
相关的教程: CSharp
收藏此教程

当前平均分: 0.0(0 次打分)

-5-4-3-2-1012345
评论主题
您的大名
您的评论
验证码 点击换一个验证码
知识库搜索: