通过实例学习C#(1)

  1. (以下内容来自http://www.fincher.org/tips/Languages/csharpLINQ.shtml)

    The obligatory example for any language,(任何语言的必须的例子)注:你懂得,Hello World!

     
    using System;
    public class HelloWorld
    {
        public static void Main(string[] args) {
    	Console.Write("Hello World!");
        }
    }
    
  2. Raw CSharp compiler(原生C#编译器)

    You can compile c# using the command line version(你可以使用命令行工具来编译C#程序)

     
    C:>csc HelloWorld.cs
    
    and then run the new program by entering(然后,通过键入HelloWorld来运行程序)
    HelloWorld
    

    You can get Nant, a build tool like the old 'make', from http://sourceforge.net/projects/nant.(你可以下载Nant从http://sourceforge.net/projects/nant,一个像老的make的编译工具)

  3. Reading Stuff(读取相关)
    1. Read an entire file into a string(将整个文件读取到一个字符串中)

      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);
              }
          }
      }
      
    2. Read a file with a single call to sReader.ReadToEnd() using streams(单独调用流文件的ReadToEnd()函数来读取文件)

       
      public static string getFileAsString(string fileName) {
         StreamReader sReader = null;
         string contents = null;
         try {
            FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            sReader = new StreamReader(fileStream);
            contents = sReader.ReadToEnd();
         } finally {
           if(sReader != null) {
               sReader.Close();
            }
         }
         return contents;
      }
      
    3. Read all the lines from a file into an array(从文件中读取所有行到一个数组中)

       
      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();
              }
          }
      }
      
    4. Read a file line by line with no error checking(没有错误检测的一行一行读取文件)

      Useful if the file may be really large.(如果一个文件真的很大的话,是很有用的)

       
      StreamReader sr = new StreamReader("fileName.txt");
      string line;
      while((line= sr.ReadLine()) != null) {
      	Console.WriteLine("xml template:"+line);
      }
      
      if (sr != null)sr.Close();  //should be in a "finally" or "using" block
      
  4. Writing Stuff(写入相关)
    1. Easy writing all text to a file(简单的将所有文本写入到一个文件)

      WriteAllText will create the file if it doesn't exist, otherwise overwrites it. It will also close the file.(WriteAllText函数将会创建文件,如果文件不存在的话;否则会覆盖已经存在的文件。它也会关闭文件)

       
      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);
              }
          }
      }
      
    2. Write a line to a file using 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(); }
      	}
      }
      }
      
      
    3. Access files with "using"(通过using关键字来写入文件)

      "using" does an implicit call to Dispose() when the using block is complete. With files this will close the file. The following code shows that using does indeed close the file, otherwise 5000 open files would cause problems.(当using块完成之后,using会隐性的调用Dispose函数,这样会关闭这个文件。下面的代码显示了,using确实会关闭文件,否则5000次打开文件会导致问题发生的。)

       
      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();
          }
      }
      
      
    4. "using" as "typedef" (a la "C")(using像typedef)

      "C" allows you to alias one type as another with typedef. In C# you can do this with "using" (can we create another overload for "using" just to make it more confusing?) Everywhere the type "RowCollection" is used, C# will understand it to be of type "List<Node>"(在C中,你可以使用typedef来为一个类型定义一个别名。在C#中,你可以使用using来完成。每个当RowCollection被用到的地方,C#都会将它理解成List<Node>类型的。)

      using RowCollection = List<Node>;
    5. Write a very simple XML fragment the hard way.(用硬性方法来写一个很简单的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);
      }
      
    6. Write a very simple XML fragment the easier way(写入一个简单的XML段的最简单的方法)

       
      StringWriter stringWriter = new StringWriter();
      XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
      xmlTextWriter.Formatting = Formatting.Indented;
      xmlDocument.WriteTo(xmlTextWriter); //xmlDocument can be replaced with an XmlNode
      xmlTextWriter.Flush();
      Console.Write(stringWriter.ToString());
      
    7. To write any object or some collections to xml(写入任何对象或集合到xml中)

      Object must have a default constructor.(对象必须有一个默认的构造函数)

      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());
      }
      
    8. And this should turn the xml back into an object(下面的程序将会将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);
      }
      
      
        
    9. 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
      
      
    10. Formatting decimals in strings using String.Format()(使用String.Format()函数来格式化十进制字符串)

      More info at www.codeproject.com

       
      s.Append(String.Format("Completion Ratio: {0:##.#}%",100.0*completes/count));
      
      or use the ToString() method on the double object:(或者使用double对象的ToString函数)
       
      s.Append(myDouble.ToString("###.###")
      
      or (或者)
       
      String.Format("{0,8:F3}",this.OnTrack)
      
    11. Format DateTime objects(格式化DateTime对象)

       
      DateTime.Now.ToString("yyyyMMdd-HHmm"); // will produce '20060414-1529'
      【更多阅读】
      
      
  1. [原]PjConvertImageFormat:用FreeImage.NET写的一个35种图像格式转换程序
  2. [原]Cls_Ini.cls:VB写的操作ini配置文件的类
  3. [原]PjConvertImageFormat:用FreeImage.NET写的一个35种图像格式转换程序
  4. [原]GetAlpha:C#实现获取网页验证码图片,并识别出其中的字母
  5. [原]IniFile.cs:C#来操作ini配置文件
  6. [译]用C#检测你的打印机是否连接
  7. [原]Hotkey.cs:为应用程序添加热键
  8. [原]GetAlpha:C#实现获取网页验证码图片,并识别出其中的字母
  9. [原]DownloadWebImages:下载某页面上的所有图片
  10. [原]QQHelper:QQ大家来找茬 辅助工具 外挂
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 网络通信开发训练-32个实例 C# 网络通信开发训练 实例01 更改计算机名称...... 670 实例02 通过计算机名获取IP地址...... 672 实例03 通过IP地址获取主机名称...... 673 实例04 修改本机IP地址...... 674 实例05 得到本机MAC地址...... 677 实例06 获得系统打开的端口和状态...... 678 实例07 更改DNS地址...... 680 14.2 远程控制...... 681 实例08 远程控制计算机...... 682 实例09 远程服务控制...... 683 14.3 网络复制文件...... 686 实例10 网络中的文件复制...... 686 14.4 局域网管理...... 688 实例11 在局域网内发送信息...... 688 实例12 获取网络中所有工作组名称...... 690 实例13 列出工作组中所有计算机...... 692 实例14 获取网络中某台计算机的磁盘信息...... 693 实例15 映射网络驱动器...... 694 14.5 网络连接与通信...... 696 实例16 编程实现Ping操作...... 696 14.6 网络聊天室...... 698 实例17 利用C#设计聊天程序...... 698 实例18 编写网络聊天室...... 700 18.1 Windows服务开发...... 782 实例01 将局域网聊天程序开发成Windows服务...... 782 第15章 Web编程....... 703 15.1 浏览器应用...... 704 实例01 制作自己的网络浏览软件...... 704 实例02 XML数据库文档的浏览...... 708 15.2 上网控制...... 710 实例03 定时上Internet. 710 实例04 监测当前网络连接状态...... 712 15.3 邮件管理...... 713 实例05 收取电子邮件...... 713 实例06 SMTP协议发送电子邮件...... 717 15.4 网上信息提取...... 719 实例07 提取并保存网页源码...... 719 实例08 提取网页标题...... 722 16通用实例训练 实例01 CS结构Tcp通信训练 实例02 CS结构UDP通信训练 实例03 P2P技术训练 实例04 TCP发送文件训练
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值