⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cessentials_examples.htm

📁 国外CSharp入门书,包含的代码可作为学习CSharp的参考代码
💻 HTM
📖 第 1 页 / 共 5 页
字号:
class ProbeSvr {  static void Main(string[] args) {    // Get instance of WebRequest ABC, convert to HttpWebRequest    WebRequest req = WebRequestFactory.Create(args[0]);    HttpWebRequest httpReq = (HttpWebRequest)req;    // Access HTTP-specific features such as User-Agent    httpReq.UserAgent = "CSPRProbe/1.0";    // Retrieve response and print to console    WebResponse resp = req.GetResponse();    HttpWebResponse httpResp = (HttpWebResponse)resp;    Console.WriteLine(httpResp.Server);  }}// QOTDListener.cs - compile with /r:System.Net.dll // Run QOTDListener.exe to service incoming QOTD requestsusing System;using System.Net;using System.Net.Sockets;using System.Text;class QOTDListener {  static string[] quotes = {@"Sufficiently advanced magic is indistinguishable from technology -- Terry Pratchett", @"Sufficiently advanced technology is indistinguishable from magic -- Arthur C Clarke" };  static void Main() {    // Start a TCP listener on port 17    TCPListener l = new TCPListener(17);    l.Start();    Console.WriteLine("Waiting for clients to connect");    Console.WriteLine("Press Ctrl+C to quit...");    int numServed = 1;    while (true) {      // Block waiting for an incoming socket connect request      Socket s = l.Accept();      // Encode alternating quotes as bytes for sending       Char[] carr = quotes[numServed%2].ToCharArray();      Byte[] barr = Encoding.ASCII.GetBytes(carr);      // Return data to client, then clean up socket & repeat      s.Send(barr, barr.Length, 0);      s.Shutdown(SocketShutdown.SdBoth);      s.Close();      Console.WriteLine("{0} quotes served...", numServed++);    }  }}</pre><p><b>Using DNS</b><p><pre>// DNSLookup.cs - compile with /r:System.Net.dll// Run DNSLookup.exe &lt;servername&gt; to determine IP addressesusing System;using System.Net;class DNSLookup {  static void Main(string[] args) {    IPHostEntry he = DNS.GetHostByName(args[0]);    IPAddress[] addrs = he.AddressList;    foreach (IPAddress addr in addrs)      Console.WriteLine(addr);  }}</pre><p><h4><u>Threading</u></h4><p><pre>using System;using System.Threading;class ThreadTest {  static void Main() {  Thread t = new Thread(new ThreadStart(Go));    t.Start();    Go();  }  static void Go() {    for (char c='a'; c&lt;='z'; c++ )      Console.Write(c);  }}abcdabcdefghijklmnopqrsefghjiklmnopqrstuvwxyztuvwxyz</pre><p><b>Thread Synchronization</b><p><b>The Lock Statement</b><p><pre>using System;using System.Threading;class LockTest {  static void Main() {    LockTest lt = new LockTest ();    Thread t = new Thread(new ThreadStart(lt.Go));    t.Start();    lt.Go();  }  void Go() {    lock(this)      for ( char c='a'; c&lt;='z'; c++)        Console.Write(c);  }}abcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzSystem.Threading.Monitor.Enter(expression);try {  ...}finally {  System.Threading.Monitor.Exit(expression);}</pre><p><b>Pulse and Wait</b><p><pre>using System;using System.Threading;class MonitorTest {  static void Main() {    MonitorTest mt = new MonitorTest();    Thread t = new Thread(new ThreadStart(mt.Go));    t.Start();    mt.Go();  }  void Go() {    for ( char c='a'; c&lt;='z'; c++)      lock(this) {        Console.Write(c);        Monitor.Pulse(this);        Monitor.Wait(this);      }  }}aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz</pre><p><b>Deadlocks</b><p><pre>  void Go() {    for ( char c='a'; c&lt;='z'; c++)      lock(this) {        Console.Write(c);        Monitor.Pulse(this);        if (c&lt;'z')          Monitor.Wait(this);      }  }</pre><p><h4><u>Reflection</u></h4><p><b>Retrieving a Type Directly</b><p><pre>Type t = Type.GetType("System.Int32");Type t = typeof(System.Int32);</pre><p><b>Reflecting Over a Type Hierarchy</b><p><pre>using System;using System.Reflection;class Test {  static void Main() {    object o = new Object();    DumpTypeInfo(o.GetType());    DumpTypeInfo(typeof(int));    DumpTypeInfo(Type.GetType("System.String"));  }  static void DumpTypeInfo(Type t) {    Console.WriteLine("Type: {0}", t);    // Retrieve the list of members in the type    MemberInfo[] miarr = t.GetMembers(BindingFlags.LookupAll);    // Print out details on each of them    foreach (MemberInfo mi in miarr)      Console.WriteLine("  {0}={1}", mi.MemberType.Format(), mi);  }}</pre><p><b>Late Binding to Types</b><p><pre>// Greeting.cs - compile with /t:librarypublic abstract class Greeting {   public abstract void SayHello();}// English.cs - compile with /t:library /r:Greeting.dllusing System;public class AmericanGreeting : Greeting {  private string msg = "Hey, dude. Wassup!";  public override void SayHello() {    Console.WriteLine(msg);  }}public class BritishGreeting : Greeting {  private string msg = "Good morning, old chap!";  public override void SayHello() {    Console.WriteLine(msg);  }}// SayHello.cs - compile with /r:Greeting.dll// Run with SayHello.exe &lt;dllname1&gt; &lt;dllname2&gt; ... &lt;dllnameN&gt;using System;using System.Reflection;class Test {  static void Main (string[] args) {    // Iterate over the cmd-line options,    // trying to load each assembly    foreach (string s in args) {      Assembly a = Assembly.LoadFrom(s);            // Pick through all the public type, looking for      // subtypes of the abstract base class Greeting      foreach (Type t in a.GetTypes())        if (t.IsSubclassOf(typeof(Greeting))) {          // Having found an appropriate subtype, create it          object o = Activator.CreateInstance(t);          // Retrieve the SayHello MethodInfo & invoke it          MethodInfo mi = t.GetMethod("SayHello");          mi.Invoke(o, null);        }    }  }}Hey, dude. Wassup!Good morning, old chap!</pre><p><b>Forms of Activation</b><p><pre>object o = Activator.CreateInstance("Assem1.dll",                                                  "Friendly.Greeting");</pre><p><b>Advanced Uses of Reflection</b> <p><pre>// InControl.cs - compile with /r:Greeting.dll,English.dllusing System;using System.Reflection;class TestReflection {  // Note: This method requires the ReflectionPermission perm.  static void ModifyPrivateData(object o, string msg) {    // Get a FieldInfo type for the private data member    Type t = o.GetType();     FieldInfo fi = t.GetField("msg", BindingFlags.NonPublic|                                     BindingFlags.Instance);    // Use the FieldInfo to adjust the data member value    fi.SetValue(o, msg);  }  static void Main() {    // Create instances of both types    BritishGreeting bg = new BritishGreeting();    AmericanGreeting ag = new AmericanGreeting();    // Adjust the private data via reflection    ModifyPrivateData(ag, "Things are not the way they seem");    ModifyPrivateData(bg, "The runtime is in total control!");        // Display the modified greeting strings    ag.SayHello(); // "Things are not the way they seem"    bg.SayHello(); // "The runtime is in total control!"  }}Things are not the way they seemThe runtime is in total control!</pre><p><b>Creating New Types at Runtime</b><p><pre>using System;using System.Reflection;using System.Reflection.Emit;public class Test{  static void Main()  {    // Create a dynamic assembly in the current AppDomain    AppDomain ad = AppDomain.CurrentDomain;    AssemblyName an = new AssemblyName();    an.Name = "DynAssembly";    AssemblyBuilder ab =       ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);        // Create a module in the assembly & a type in the module    Assembly a = (Assembly)ab;    ModuleBuilder modb = a.DefineDynamicModule("DynModule");    TypeBuilder tb = modb.DefineType("AgentSmith",                                      TypeAttributes.Public);     // Add a SayHello member to the type     MethodBuilder mb = tb.DefineMethod("SayHello",                                               MethodAttributes.Public,                                       null, null);                                            // Generate the MSIL for the SayHello Member    ILGenerator ilg = mb.GetILGenerator();    ilg.EmitWriteLine("Never send a human to do a machine's job.");    ilg.Emit(OpCodes.Ret);    // Finalize the type so we can create it    tb.CreateType();    // Create an instance of the new type    Type t = Type.GetType("AgentSmith");    object o = Activator.CreateInstance(t);        // Prints "Never send a human to do a machine's job."    t.GetMethod("SayHello").Invoke(o, null);  }}</pre><p><h4><u>Custom Attributes</u></h4><p><b>Defining a New Custom Attribute</b><p><pre>using System;[AttributeUsage(AttributeTargets.ClassMembers, AllowMultiple=true)]class CrossRefAttribute : Attribute {  Type   xref;  string desc = "";  public string Description { set { desc=value; } }   public CrossRefAttribute(Type xref) { this.xref=xref; }  public override string ToString() {    string tmp = (desc.Length&gt;0) ? " ("+desc+")" : "";    return "CrossRef to "+xref.ToString()+tmp;  }			}[CrossRef(typeof(Bar), Description="Foos often hang around Bars")]class Foo {...}</pre><p><b>Retrieving a Custom Attribute at Runtime</b><p><pre>using System;[Serializable, Obsolete]class Test {  static void Main() {    Type t = typeof(Test);    object[] caarr = t.GetCustomAttributes();    Console.WriteLine("{0} has {1} custom attribute(s)",                      t, caarr.Length);    foreach (object ca in caarr)      Console.WriteLine(ca);  }}Test has 1 custom attribute(s)System.ObsoleteAttribute</pre><p><b>Dispose and Close Methods</b><p><pre>public class Worker {  ...  public void Dispose() {    // Perform normal cleanup    ...     // Mark this object finalized    GC.SuppressFinalize(this);  }  protected override void Finalize() {    Dispose();    base.Finalize();  }}</pre><p><h4><u>Interop With Native DLLs</u></h4><p><pre>int MessageBox(HWND hWnd, LPCTSTR lpText,                LPCTSTR lpCation, UINT uType);using System.Runtime.InteropServices;[DllImport("user32.dll")]static extern int MessageBox(int hWnd, string text,                              string caption, int type);</pre><b>Marshaling Common Types</b><p><pre>using System.Runtime.InteropServices;static extern int Foo([MarshalAs(UnmanagedType.LPStr)]                      string s);using System.Runtime.InteropServices;[DllImport("kernel32.dll")]static extern int GetWindowsDirectory(StringBuilder sb,                                      int maxChars);class Test {   static void Main() {      StringBuilder s = new String(256);      GetWindowsDirectory(s, 256);      Console.WriteLine(s);   }}</pre><p><b>Marshalling Classes and Structs</b><p><pre>using System.Runtime.InteropServices;[StructLayout(LayoutKind.Sequential)]class SystemTime {   public ushort wYear;    public ushort wMonth;   public ushort wDayOfWeek;    public ushort wDay;    public ushort wHour;    public ushort wMinute;    public ushort wSecond;    public ushort wMilliseconds; }class Test {   [DllImport("kernel32.dll")]   static extern void GetSystemTime(SystemTime t);   static void Main() {      SystemTime t = new SystemTime();      GetSystemTime(t);      Console.WriteLine(t.wYear);   }}</pre><p><b>In and Out Marshaling</b><p><pre>struct SystemTime {...}static extern void GetSystemTime(ref SystemTime t);static extern void Foo([in] int[] array);</pre><p><b>Callbacks from Unmanaged Code</b><p><pre>class Test {   delegate bool CallBack(int hWnd, int lParam);   [DllImport("user32.dll")]   static extern int EnumWindows(CallBack hWnd, int lParam);   static bool PrintWindow(int hWnd, int lParam) {      Console.WriteLine(hWnd);      return true;   }   static void Main() {      CallBack e = new CallBack(PrintWindow);      EnumWindows(e, 0);   }}</pre><p><h4><u>Interop With COM</u></h4><p><b>Exposing COM Objects To C#</b><p><pre>// IMAdd.cs - compile with /r:Messenger.dll// Run IMAdd.exe &lt;UserID&gt; to add an MSN Instant //   Messenger user to Contacts// Run TlbImp.exe "C:\Program Files\Messenger\msmsgs.exe" //   to create Messenger.dllusing System.Runtime.InteropServices;using Messenger; // COM API for MSN Instant Messengerclass COMConsumer {   static void Main(string[] args) {      MessengerApp m = new MessengerApp()      m.LaunchAddContactUI(args[0]);   }}</pre><p><b>Exposing C# Objects To COM</b><p><pre>[GuidAttribute("aa6b10a2-dc4f-4a24-ae5e-90362c2142c1")]public interface : IRunInfo {  [DispId(1)]  string GetRunInfo();}[GuidAttribute("b72ccf55-88cc-4657-8577-72bd0ff767bc")]public class StackSnapshot : IRunInfo {  public StackSnapshot() {    st = new StackTrace();  }  [DispId(1)]  public string GetRunInfo() {    return st.ToString();  }  private StackTrace st;}</pre><p><h3>Regular Expressions</h3><pre>using System;class TestDefaultFormats {  static void Main() {    int i = 654321;    Console.WriteLine("{0:C}", i); // $654,321.00    Console.WriteLine("{0:D}", i); // 654321    Console.WriteLine("{0:E}", i); // 6.543210E+005    Console.WriteLine("{0:F}", i); // 654321.00    Console.WriteLine("{0:G}", i); // 654321    Console.WriteLine("{0:N}", i); // 654,321.00    Console.WriteLine("{0:X}", i); // 9FBF1    Console.WriteLine("{0:x}", i); // 9fbf1  }}using System;class TestIntegerFormats {  static void Main() {    int i = 123;    Console.WriteLine("{0:C6}", i); // $123.000000    Console.WriteLine("{0:D6}", i); // 000123    Console.WriteLine("{0:E6}", i); // 1.230000E+002    Console.WriteLine("{0:G6}", i); // 123    Console.WriteLine("{0:N6}", i); // 123.000000    Console.WriteLine("{0:X6}", i); // 00007B    i = -123;    Console.WriteLine("{0:C6}", i); // ($123.000000)    Console.WriteLine("{0:D6}", i); // -000123    Console.WriteLine("{0:E6}", i); // -1.230000E+002    Console.WriteLine("{0:G6}", i); // -123    Console.WriteLine("{0:N6}", i); // -123.000000    Console.WriteLine("{0:X6}", i); // FFFF85    i = 0;    Console.WriteLine("{0:C6}", i); // $0.000000    Console.WriteLine("{0:D6}", i); // 000000    Console.WriteLine("{0:E6}", i); // 0.000000E+000    Console.WriteLine("{0:G6}", i); // 0    Console.WriteLine("{0:N6}", i); // 0.000000    Console.WriteLine("{0:X6}", i); // 000000  }}                                                using System;class TestDoubleFormats {  static void Main() {    double d = 1.23;    Console.WriteLine("{0:C6}", d); // $1.230000    Console.WriteLine("{0:E6}", d); // 1.230000E+000    Console.WriteLine("{0:G6}", d); // 1.23    Console.WriteLine("{0:N6}", d); // 1.230000    d = -1.23;    Console.WriteLine("{0:C6}", d); // ($1.230000)    Console.WriteLine("{0:E6}", d); // -1.230000E+000    Console.WriteLine("{0:G6}", d); // -1.23    Console.WriteLine("{0:N6}", d); // -1.230000    d = 0;    Console.WriteLine("{0:C6}", d); // $0.000000    Console.WriteLine("{0:E6}", d); // 0.000000E+000    Console.WriteLine("{0:G6}", d); // 0    Console.WriteLine("{0:N6}", d); // 0.000000  }}using System;class TestIntegerCustomFormats {  static void Main() {    int i = 123;    Console.WriteLine("{0:#0}", i);             // 123    Console.WriteLine("{0:#0;(#0)}", i);        // 123    Console.WriteLine("{0:#0;(#0);&lt;zero&gt;}", i); // 123    Console.WriteLine("{0:#%}", i);             // 12300%    i = -123;    Console.WriteLine("{0:#0}", i);             // -123    Console.WriteLine("{0:#0;(#0)}", i);        // (123)    Console.WriteLine("{0:#0;(#0);&lt;zero&gt;}", i); // (123)    Console.WriteLine("{0:#%}", i);             // -12300%    i = 0;    Console.WriteLine("{0:#0}", i);             // 0    Console.WriteLine("{0:#0;(#0)}", i);        // 0    Console.WriteLine("{0:#0;(#0);&lt;zero&gt;}", i); // &lt;zero&gt;    Console.WriteLine("{0:#%}", i);             // %  }}using System;class TestDoubleCustomFormats {  static void Main() {    double d = 1.23;    Console.WriteLine("{0:#.000E+00}", d);    // 1.230E+00    Console.WriteLine(      "{0:#.000E+00;(#.000E+00)}", d);        // 1.230E+00    Console.WriteLine(      "{0:#.000E+00;(#.000E+00);&lt;zero&gt;}", d); // 1.230E+00    Console.WriteLine("{0:#%}", d);           // 123%    d = -1.23;    Console.WriteLine("{0:#.000E+00}", d);    // -1.230E+00    Console.WriteLine(      "{0:#.000E+00;(#.000E+00)}", d);        // (1.230E+00)    Console.WriteLine(      "{0:#.000E+00;(#.000E+

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -