C#快速学习笔记(译)

 

下面是通过代码快速学习C#的例子。

1.学习任何语言都必定会学到的hello,world!

using System;
public class HelloWorld
{
public static void Main(string[] args) {
Console.Write("Hello World!");
}
}

2.原始的C#编译器(你可以使用下面的命令行编译C#)

C:>csc HelloWorld.cs

你将得到:

HelloWorld

详情可参见: http://sourceforge.net/projects/nant

3.读取文件

A:读取整个文件到字符串

using System;
namespace PlayingAround {
class ReadAll {
public static void Main(string[] args) {
string contents = System.IO.File.ReadAllText(@"C:\t1");
Console.Out.WriteLine("contents = " + contents);
}
}
}

B:从一个文件中读取所有行到数组中

using System;
namespace PlayingAround {
class ReadAll {
public static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines(@"C:\t1");
Console.Out.WriteLine("contents = " + lines.Length);
Console.In.ReadLine();
}
}
}

C:逐行读取文件不检查错误(对于大文件很有作用)

StreamReader sr = new StreamReader("fileName.txt");
string line;
while((line= sr.ReadLine()) != null) {
Console.WriteLine("xml template:"+line);
} if (sr != null)sr.Close(); //应该在最后或使用块

4.写文件

A:简单写入所有文本(文件不存在将创建,存在将重写,最终关闭文件)

using System;
namespace PlayingAround {
class ReadAll {
public static void Main(string[] args) {
string myText = "Line1" + Environment.NewLine + "Line2" + Environment.NewLine;
System.IO.File.WriteAllText(@"C:\t2", myText);
}
}
}

B:使用Streams将一行文字写入文件

using System;
using System.IO; public class WriteFileStuff { public static void Main() {
FileStream fs = new FileStream("c:\\tmp\\WriteFileStuff.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
try {
sw.WriteLine("Howdy World.");
} finally {
if(sw != null) { sw.Close(); }
}
}
}

C:使用using访问文件(当block完整时using隐式调用Dispose(),这也会关闭文件,下面的代码请仔细参悟。)

using System;
using System.IO; class Test {
private static void Main() {
for (int i = 0; i < 5000; i++) {
using (TextWriter w = File.CreateText("C:\\tmp\\test\\log" + i + ".txt")) {
string msg = DateTime.Now + ", " + i;
w.WriteLine(msg);
Console.Out.WriteLine(msg);
}
}
Console.In.ReadLine();
}
}

D:"using" as "typedef" (a la "C")

using RowCollection = List<Node>;

E:写一个简单的XML片段的艰难方法

static void writeTree(XmlNode xmlElement, int level) {
String levelDepth = "";
for(int i=0;i<level;i++)
{
levelDepth += " ";
}
Console.Write("\n{0}<{1}",levelDepth,xmlElement.Name);
XmlAttributeCollection xmlAttributeCollection = xmlElement.Attributes;
foreach(XmlAttribute x in xmlAttributeCollection)
{
Console.Write(" {0}='{1}'",x.Name,x.Value);
}
Console.Write(">");
XmlNodeList xmlNodeList = xmlElement.ChildNodes;
++level;
foreach(XmlNode x in xmlNodeList)
{
if(x.NodeType == XmlNodeType.Element)
{
writeTree((XmlNode)x, level);
}
else if(x.NodeType == XmlNodeType.Text)
{
Console.Write("\n{0} {1}",levelDepth,(x.Value).Trim());
}
}
Console.Write("\n{0}</{1}>",levelDepth,xmlElement.Name);
}

F:写一个简单XML片段的简单方法

StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
xmlTextWriter.Formatting = Formatting.Indented;
xmlDocument.WriteTo(xmlTextWriter); //xmlDocument 可以被 XmlNode替代
xmlTextWriter.Flush();
Console.Write(stringWriter.ToString());

G:写入XML的对象或者集合必须有一个默认的构造函数

public static string SerializeToXmlString(object objectToSerialize) {
MemoryStream memoryStream = new MemoryStream();
System.Xml.Serialization.XmlSerializer xmlSerializer =
new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType());
xmlSerializer.Serialize(memoryStream, objectToSerialize);
ASCIIEncoding ascii = new ASCIIEncoding();
return ascii.GetString(memoryStream.ToArray());
}

H:并且它也要能使XML转换成对象

public static object DeSerializeFromXmlString(System.Type typeToDeserialize, string xmlString) {
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xmlString);
MemoryStream memoryStream = new MemoryStream(bytes);
System.Xml.Serialization.XmlSerializer xmlSerializer =
new System.Xml.Serialization.XmlSerializer(typeToDeserialize);
return xmlSerializer.Deserialize(memoryStream);
} Example
[Test]
public void GetBigList() {
var textRepository = ObjectFactory.GetInstance<ITextRepository>();
List<BrandAndCode> brandAndCodeList = textRepository.GetList(...);
string xml = SerializeToXmlString(brandAndCodeList);
Console.Out.WriteLine("xml = {0}", xml);
var brandAndCodeList2 = DeSerializeFromXmlString(typeof (BrandAndCode[]), xml);
}

I:关于类型的几句话

类型一般包括数据成员和方法成员,比如int,它就包括了一个值和一个方法ToString()。

C#中所有值都是类型的实例。

C#提供了内置的,或预定义的,直接的语言,被编译器理解,并为他们划出关键词。这些值的类型包括SBYTE,短整型,长字节,USHORT(无符号短整型),UINT(无符号整型),ULONG(无符号长整型),浮点数,双精度浮点数胡,小数,布尔和char(字符型)。预定义的引用类型是字符串和对象。这些类型分为不同的类型在“系统”命名空间中也有别名,如整型int被重命名为System.Int32 。

C#在系统的命名空间中还提供了内置的类型如DateTime类型,当然编译器并不能直接知道这些类型。

所有C#类型均在下面几种分类之一:

值类型(大多数内置类型如int、double和自定义struct、没有方法只为一个值得enum类型)

引用类型(任何类,数组等)

泛型类型参数,指针类型

使用类自定义的类型

J:Write formated output:

int k = 16;
Console.WriteLine(" '{0,-8}'",k); // produces: '16 '
Console.WriteLine(" '{0,8}'",k); // produces: ' 16'
Console.WriteLine(" '{0,8}'","Test"); // produces: ' Test'
Console.WriteLine(" '{0,-8}'","Test");// produces: 'Test '
Console.WriteLine(" '{0:X}'",k); //(in HEX) produces: '10'
Console.WriteLine(" '{0:X10}'",k); //(in HEX) produces:'0000000010'
Console.WriteLine( 1234567.ToString("#,##0")); // writes with commas: 1,234,567

K:命名空间(命名空间的作用是为了减少混乱)

using Monkeys = Animals.Mammals.Primates;
class MyZoo { Monkeys.Howler; }

L:使用String.Format()把decimals 变成strings

s.Append(String.Format("Completion Ratio: {0:##.#}%",100.0*completes/count));

或者使用ToString()方法在 double 对象上:

s.Append(myDouble.ToString("###.###")

又或者

String.Format("{0,8:F3}",this.OnTrack)

M:格式化DateTime对象

DateTime.Now.ToString("yyyyMMdd-HHmm"); // will produce '20060414-1529'

5.构造函数,静态构造函数和析构函数的​​示例:

using System;
class Test2
{
static int i;
static Test2() { // a constructor for the entire class called
//once before the first object created
i = 4;
Console.Out.WriteLine("inside static construtor...");
}
public Test2() {
Console.Out.WriteLine("inside regular construtor... i={0}",i);
}
~Test2() { // destructor (hopefully) called for each object
Console.Out.WriteLine("inside destructor");
} static void Main(string[] args)
{
Console.Out.WriteLine("Test2");
new Test2();
new Test2();
}
}

运行:

inside static construtor...
Test2
inside regular construtor... i=4
inside regular construtor... i=4
inside destructor
inside destructor

未完待续。

鹜落霜洲,雁横烟渚,分明画出秋色。暮雨乍歇,小楫夜泊,宿苇村山驿。何人月下临风处,起一声羌笛。离愁万绪,闲岸草、切切蛩吟似织。 为忆芳容别后,水遥山远,何计凭鳞翼。想绣阁深沉,争知憔悴损,天涯行客。楚峡云归,高阳人散,寂寞狂踪迹。望京国。空目断、远峰凝碧。
 
分类: C#

C#快速学习的更多相关文章

  1. 60分钟Python快速学习(给发哥一个交代)

    60分钟Python快速学习 之前和同事谈到Python,每次下班后跑步都是在听他说,例如Python属于“胶水语言啦”,属于“解释型语言啦!”,是“面向对象的语言啦!”,另外没有数据类型,逻辑全靠空 ...

  2. LinqPad工具:帮你快速学习Linq

    LinqPad工具:帮你快速学习Linq 参考: http://www.cnblogs.com/li-peng/p/3441729.html ★:linqPad下载地址:http://www.linq ...

  3. 快速学习C语言一: Hello World

    估计不会写C语言的同学也都听过C语言,从头开始快速学一下吧,以后肯定能用的上. 如果使用过其它类C的语言,如JAVA,C#等,学C的语法应该挺快的. 先快速学习并练习一些基本的语言要素,基本类型,表达 ...

  4. 【Java线程池快速学习教程】

    1. Java线程池 线程池:顾名思义,用一个池子装载多个线程,使用池子去管理多个线程. 问题来源:应用大量通过new Thread()方法创建执行时间短的线程,较大的消耗系统资源并且系统的响应速度变 ...

  5. 【Java的JNI快速学习教程】

    1. JNI简介 JNI是Java Native Interface的英文缩写,意为Java本地接口. 问题来源:由于Java编写底层的应用较难实现,在一些实时性要求非常高的部分Java较难胜任(实时 ...

  6. 快速学习bootstrap前台框架

    W3c里的解释 使用bootstrap需要注意事项 1.  在html文件第一行要加上<!doctype html>[s1] 2.  导入bootstrap.min.css文件 3.  导 ...

  7. C#快速学习笔记(译)

    下面是通过代码快速学习C#的例子. 1.学习任何语言都必定会学到的hello,world! using System; public class HelloWorld { public static ...

  8. Dapper快速学习

    Dapper快速学习 我们都知道ORM全称叫做Object Relationship Mapper,也就是可以用object来map我们的db,而且市面上的orm框架有很多,其中有一个框架 叫做dap ...

  9. ASP.NET快速学习方案(.NET菜鸟的成长之路)

    想要快速学习ASP.NET网站开发的朋友可以按照下面这个学习安排进度走.可以让你快速入门asp.net网站开发!但也局限于一般的文章类网站!如果想学习更多的技术可以跟着我的博客更新走!我也是一名.NE ...

  10. 60分钟Python快速学习(转)

    60分钟Python快速学习(给发哥一个交代) 阅读目录 第一步:开发环境搭建: 第一个Python功能:初识Python 02.Python中定义变量不需要数据类型 03.在Pythod中定义方法 ...

随机推荐

  1. e.target 和 e.srcElement 的使用问题

    ie 下的event.srcElement从字面上可以看出来有以下关键字:事件.源(它的意思就是:当前事件的源), 我们可以调用他的各种属性就像:document.getElementById(&qu ...

  2. BS导出csv文件的通用方法(.net)

    最近把以前项目里用的导出文件的功能提取成了dll,通过读取Attribute来得到要导出的表头(没有支持多语言),使用时只要组织好要导出的数据,调用方法就好了,希望对大家有用. 使用时只需引用下载包里 ...

  3. JAVA 代码生成。SimpleCaptcha

    去官方网站下载Jar包: http://simplecaptcha.sourceforge.net/ Javadocs: http://simplecaptcha.sourceforge.net/ja ...

  4. windows 开机自动登录,或者说是开机后自动进入桌面

    这篇文章,对于XP以及XP以上版本有效,包括Windows Server服务器操作系统. 1.原理 --Windows自动登录的原理是,开始后,自动输入登录所使用的账号的用户名和密码,并且自动进入桌面 ...

  5. Asterisk 未来之路3.0_0003

    原文:Asterisk 未来之路3.0_0003 Asterisk: The Hacker's PBX 如果电信公司忽视了asterisk,那么正在处于危险中.asterisk 良好的扩展性,能够创建 ...

  6. [译]Java 垃圾回收的监控和分析

    说明:这篇文章来翻译来自于Javapapers 的Java Garbage Collection Monitoring and Analysi 在这个系列的Java垃圾回收教程中,我们将看到可用于垃圾 ...

  7. ubuntu下的词典的安装

    因为从事开发,安装一个词典是很有必要,文中介绍安装openyoudao和stardic两个软件的方法 一.openyoudao的安装 因为是由window转来学ubuntu的,所以总是想安装和wind ...

  8. Web前端框架与类库

    Web前端框架与类库的思考 说起前端框架,我也是醉了.现在去面试或者和同行聊天,动不动就这个框架碉堡了,那个框架好犀利. 当然不是贬低框架,只是有一种杀鸡焉用牛刀的感觉.网站技术是为业务而存在的,除此 ...

  9. .net中,控件(Name)属性或ID属性的常见命名规则

    控件名称 缩写 介绍 公共控件   Button btn 按钮 CheckBox chk 复选框 CheckedListBox ckl 显示一个项列表,其中每一项左侧都有一个复选框 ComboBox ...

  10. 一键部署mono 免费空间

    一键部署mono 免费空间支持c# 再也不担心伙食费换空间了 一直以来 部署mono 都是很头疼的事情 因为是我在是不熟悉非win环境,今天偶然发现这个项目,挺好的,分享下 https://githu ...