C#快速学习
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#快速学习的更多相关文章
- 60分钟Python快速学习(给发哥一个交代)
60分钟Python快速学习 之前和同事谈到Python,每次下班后跑步都是在听他说,例如Python属于“胶水语言啦”,属于“解释型语言啦!”,是“面向对象的语言啦!”,另外没有数据类型,逻辑全靠空 ...
- LinqPad工具:帮你快速学习Linq
LinqPad工具:帮你快速学习Linq 参考: http://www.cnblogs.com/li-peng/p/3441729.html ★:linqPad下载地址:http://www.linq ...
- 快速学习C语言一: Hello World
估计不会写C语言的同学也都听过C语言,从头开始快速学一下吧,以后肯定能用的上. 如果使用过其它类C的语言,如JAVA,C#等,学C的语法应该挺快的. 先快速学习并练习一些基本的语言要素,基本类型,表达 ...
- 【Java线程池快速学习教程】
1. Java线程池 线程池:顾名思义,用一个池子装载多个线程,使用池子去管理多个线程. 问题来源:应用大量通过new Thread()方法创建执行时间短的线程,较大的消耗系统资源并且系统的响应速度变 ...
- 【Java的JNI快速学习教程】
1. JNI简介 JNI是Java Native Interface的英文缩写,意为Java本地接口. 问题来源:由于Java编写底层的应用较难实现,在一些实时性要求非常高的部分Java较难胜任(实时 ...
- 快速学习bootstrap前台框架
W3c里的解释 使用bootstrap需要注意事项 1. 在html文件第一行要加上<!doctype html>[s1] 2. 导入bootstrap.min.css文件 3. 导 ...
- C#快速学习笔记(译)
下面是通过代码快速学习C#的例子. 1.学习任何语言都必定会学到的hello,world! using System; public class HelloWorld { public static ...
- Dapper快速学习
Dapper快速学习 我们都知道ORM全称叫做Object Relationship Mapper,也就是可以用object来map我们的db,而且市面上的orm框架有很多,其中有一个框架 叫做dap ...
- ASP.NET快速学习方案(.NET菜鸟的成长之路)
想要快速学习ASP.NET网站开发的朋友可以按照下面这个学习安排进度走.可以让你快速入门asp.net网站开发!但也局限于一般的文章类网站!如果想学习更多的技术可以跟着我的博客更新走!我也是一名.NE ...
- 60分钟Python快速学习(转)
60分钟Python快速学习(给发哥一个交代) 阅读目录 第一步:开发环境搭建: 第一个Python功能:初识Python 02.Python中定义变量不需要数据类型 03.在Pythod中定义方法 ...
随机推荐
- SQL Profile (总结4)--使用演示示例
前提:sql profile工具的相关视图 dba_sql_profile 10g: sys.sqlprof$attr & sqlprof$ 11g: sys.sqlobj$data & ...
- php_cawler_html嵌套标签清洗
主要处理 嵌套 div,正则无法很好的处理清洗 比如文本: 想要移除 class =quizPutTag 的div ,内部可能嵌套的还有未知层级的div[前提是html文本段是闭合标签的] 这是< ...
- linux_shell_轮询触发启动脚本
while [ 1 ]do length=`redis-cli -h *.*.*.* -p 8000 llen eq` while [ $length -gt 1 ] do echo "le ...
- ios结构体httpPost头结构
ios结构体httpPost头结构 by 吴雪莹 NSString* urlStr = @"; NSURL* url = [NSURL URLWithString:urlStr]; NSMu ...
- Forms身份验证和基于Role的权限验证
Forms身份验证和基于Role的权限验证 从Membership到SimpleMembership再到ASP.NET Identity,ASP.NET每一次更换身份验证的组件,都让我更失望.Memb ...
- jQuery组织您钞四----jQuery操作DOM
一.采用jQuery创建节点 节点是DOM基础设施.依据DOM产品规格,Node是一个很宽泛的概念,包含元素.属性.正文.档..实际开发过程中,要创建动态内容,主要操作的节点包括元素. 属性和文本. ...
- 观察者模式的程序实例C++
一.什么是观察者模式 Observer模式也叫观察者模式,是由GoF提出的23种软件设计模式的一种.Observer模式是行为模式之中的一个,它的作用是当一个对象的状态发生变化时,可以自己主动通知其它 ...
- mvc之验证IEnumerable<T> 类型,多选框验证
原文:mvc之验证IEnumerable<T> 类型,多选框验证 假设我们有这么一种需求,我们要同时添加年级和年级下面的多个班级,我们一般会像下面这种做法. Action中我们这样接收: ...
- IS2009制作Oracle 静默安装包(一)感谢空白先生特许授权
原文:IS2009制作Oracle 静默安装包(一)感谢空白先生特许授权 上一篇: MyEclipse中消除frame引起的“the file XXX can not be found.Please ...
- Android从无知到有知——NO.4
因为我们做的是手机安全卫士,因此,我们需要一个地图定位功能,些相关的项目,也有一些教程.到百度官方下载了相关的jar包和API,但自己建项目的时候却不是那么顺利,bug不断,弄得心烦意乱,最后最终臣服 ...