码迷,mamicode.com
首页 > Windows程序 > 详细

C#编程之C#基础(三)

时间:2019-11-13 13:11:45      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:nbsp   修改   space   using   public   str   world   color   pre   

今天我们讲解一下命名空间与using语句:

命名空间提供了一种组织相关类和其他类型的方式。命名空间是一种逻辑组合。命名空间可以嵌套其他的命名空间,为类型创建层次结构,如下:

 1 namespace a
 2 {
 3     namespace b
 4    {
 5          public class string  str
 6         {
 7               return "hello world." ;
 8         }
 9    }
10 }    

当然也可以将其化简为:

1 namespace a.b
2 {
3     public class string str
4    {
5         return "hello world." ;
6    }
7 }

 

对于using语句的用法,先看以下代码(这里我们先将上一章的例子作为修改对象):

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 using other = second.third.basics;
 8 
 9 namespace First
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Console.WriteLine("This isn‘t at all like Java!");
16             //define a class object base on another namesapce
17             other::namespaceExample nsex = new other::namespaceExample();
18             Console.WriteLine(nsex.getnamespace());
19             Console.ReadLine();
20             return;
21         }
22     }
23 }
24 namespace second.third.basics
25 {
26     class  namespaceExample
27     {
28         public string getnamespace()
29         {
30             return this.GetType().Namespace;
31         }
32     }
33 }

这里我们定义两个命名空间类型,其中第二个命名空间嵌套了third和basics命名空间(.third.basics表示),因为这个名称我觉得太长了,这里用using关键字将命名空间指定了别名other:

  using other = second.third.basics; 在调用第二个命名空间内的类时,可以直接创建其内的类型对象: other::namespaceExample nsex = new other::namespaceExample(); 

控制台IO

输出流常用格式: {n,w}; n代表参数索引,w代表宽度值:

1 int i=6543;
2 int h=32;
3 Console.WriteLine("{0,5}\n+{1,4}\n--------\n{2,5}",i,j,i+j);

输出竖式计算加法:

1  9892
2 +  33
3 --------
4  9925

同样,C#支持添加一个格式字符串和精度:

 Console.WriteLine("{0,6:C0}\n+{1,5:C0}\n--------\n{2,6:C0}",i,j,i+j); 以货币形式输出,精度为0位小数点

$9,892
+  $33
--------
$9,925

格式字符串要放在给出参数格式和字段宽度标记后面,并用一个冒号分开,紧接着是精度取值。

也可以用#来代替这些格式字符串,代表没有格式字符串,0代表0位小数点。

Console.WriteLine("{0,6:#0}\n+{1,5:#0}\n--------\n{2,6:#0}",i,j,i+j);
1   9892
2 +   33
3 --------
4   9925

 

C#编程之C#基础(三)

标签:nbsp   修改   space   using   public   str   world   color   pre   

原文地址:https://www.cnblogs.com/lumao1122-Milolu/p/11847831.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!