C#快速学习笔记(译)_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > C#快速学习笔记(译)

C#快速学习笔记(译)

 2013/9/23 17:06:55  倾杯天涯  博客园  我要评论(0)
  • 摘要:下面是通过代码快速学习C#的例子。1.学习任何语言都必定会学到的hello,world!usingSystem;publicclassHelloWorld{publicstaticvoidMain(string[]args){Console.Write("HelloWorld!");}}2.原始的C#编译器(你可以使用下面的命令行编译C#)C:>cscHelloWorld.cs你将得到:HelloWorld详情可参见:http://sourceforge
  • 标签:笔记 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

未完待续。

 

发表评论
用户名: 匿名