C# System API : System ex 2
1AttributeTargets.All
using System; using System.Reflection; [AttributeUsage(AttributeTargets.All)] class RemarkAttribute : Attribute { string remarkValue; public RemarkAttribute(string comment) { remarkValue = comment; } public string remark { get { return remarkValue; } } } [RemarkAttribute("This class uses an attribute.")] class UseAttrib { // ... } public class AttribDemo { public static void Main() { Type t = typeof(UseAttrib); Console.Write("Attributes in " + t.Name + ": "); object[] attribs = t.GetCustomAttributes(false); foreach(object o in attribs) { Console.WriteLine(o); } Console.Write("Remark: "); // Retrieve the RemarkAttribute. Type tRemAtt = typeof(RemarkAttribute); RemarkAttribute ra = (RemarkAttribute) Attribute.GetCustomAttribute(t, tRemAtt); Console.WriteLine(ra.remark); } }
2 AttributeTargets.Struct
using System; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct,Inherited = false)] public class ClassVersionAttribute : System.Attribute { public ClassVersionAttribute(string target) : this(target, target) { } public ClassVersionAttribute(string target,string current) { m_TargetVersion = target; m_CurrentVersion = current; } private bool m_UseCurrentVersion = false; public bool UseCurrentVersion { set { if (m_TargetVersion != m_CurrentVersion) { m_UseCurrentVersion = value; } } get { return m_UseCurrentVersion; } } private string m_CurrentName; public string CurrentName { set { m_CurrentName = value; } get { return m_CurrentName; } } private string m_TargetVersion; public string TargetVersion { get { return m_TargetVersion; } } private string m_CurrentVersion; public string CurrentVersion { get { return m_CurrentVersion; } } }
3 AttributeTargets.Class
using System; using System.Reflection; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] public class Creator : System.Attribute { public Creator(string name, string date) { this.name = name; this.date = date; version = 0.1; } string date; string name; public double version; } [Creator("T", "05/01/2001", version = 1.1)] class MainClass { static public void Main(String[] args) { for (int i = 0; i < args.Length; ++i) System.Console.WriteLine("Args[{0}] = {1}", i, args[i]); } }
4 BitConverter.GetBytes
using System; using System.Net; using System.Text; public class BinaryDataTest { public static void Main() { int test1 = 45; double test2 = 3.14159; int test3 = -1234567890; bool test4 = false; byte[] data = new byte[1024]; string output; data = BitConverter.GetBytes(test1); output = BitConverter.ToString(data); Console.WriteLine("test1 = {0}, string = {1}", test1, output); data = BitConverter.GetBytes(test2); output = BitConverter.ToString(data); Console.WriteLine("test2 = {0}, string = {1}", test2, output); data = BitConverter.GetBytes(test3); output = BitConverter.ToString(data); Console.WriteLine("test3 = {0}, string = {1}", test3, output); data = BitConverter.GetBytes(test4); output = BitConverter.ToString(data); Console.WriteLine("test4 = {0}, string = {1}", test4, output); } }
5 BitConverter.ToString
using System; using System.IO; class MainClass { public static byte[] DecimalToByteArray (decimal src){ using (MemoryStream stream = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(stream)){ writer.Write(src); return stream.ToArray(); } } } public static decimal ByteArrayToDecimal (byte[] src){ using (MemoryStream stream = new MemoryStream(src)){ using (BinaryReader reader = new BinaryReader(stream)){ return reader.ReadDecimal(); } } } public static void Main() { byte[] b = null; b = BitConverter.GetBytes(true); Console.WriteLine(BitConverter.ToString(b)); Console.WriteLine(BitConverter.ToBoolean(b, 0)); b = BitConverter.GetBytes(3678); Console.WriteLine(BitConverter.ToString(b)); Console.WriteLine(BitConverter.ToInt32(b, 0)); b = DecimalToByteArray(285998345545.563846696m); Console.WriteLine(BitConverter.ToString(b)); Console.WriteLine(ByteArrayToDecimal(b)); } }
6 BitConverter.ToInt32
using System; using System.IO; class MainClass { public static byte[] DecimalToByteArray (decimal src){ using (MemoryStream stream = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(stream)){ writer.Write(src); return stream.ToArray(); } } } public static decimal ByteArrayToDecimal (byte[] src){ using (MemoryStream stream = new MemoryStream(src)){ using (BinaryReader reader = new BinaryReader(stream)){ return reader.ReadDecimal(); } } } public static void Main() { byte[] b = null; b = BitConverter.GetBytes(true); Console.WriteLine(BitConverter.ToString(b)); Console.WriteLine(BitConverter.ToBoolean(b, 0)); b = BitConverter.GetBytes(3678); Console.WriteLine(BitConverter.ToString(b)); Console.WriteLine(BitConverter.ToInt32(b, 0)); b = DecimalToByteArray(285998345545.563846696m); Console.WriteLine(BitConverter.ToString(b)); Console.WriteLine(ByteArrayToDecimal(b)); } }
7 BitConverter.ToBoolean
using System; using System.IO; class MainClass { public static byte[] DecimalToByteArray (decimal src){ using (MemoryStream stream = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(stream)){ writer.Write(src); return stream.ToArray(); } } } public static decimal ByteArrayToDecimal (byte[] src){ using (MemoryStream stream = new MemoryStream(src)){ using (BinaryReader reader = new BinaryReader(stream)){ return reader.ReadDecimal(); } } } public static void Main() { byte[] b = null; b = BitConverter.GetBytes(true); Console.WriteLine(BitConverter.ToString(b)); Console.WriteLine(BitConverter.ToBoolean(b, 0)); b = BitConverter.GetBytes(3678); Console.WriteLine(BitConverter.ToString(b)); Console.WriteLine(BitConverter.ToInt32(b, 0)); b = DecimalToByteArray(285998345545.563846696m); Console.WriteLine(BitConverter.ToString(b)); Console.WriteLine(ByteArrayToDecimal(b)); } }
8 ConsoleColor.Red
using System; public class Test{ static void Main(string[] args){ Console.Title = "Standard Console"; Console.ForegroundColor = ConsoleColor.Red; Console.BackgroundColor = ConsoleColor.Green; Console.WriteLine("Press Enter to change the Console's appearance."); Console.ReadLine(); } }
9 ConsoleKeyInfo.Key
using System; using System.Collections.Generic; class MainClass { public static void Main() { ConsoleKeyInfo key; List<char> input = new List<char>(); do{ key = Console.ReadKey(true); if (key.Key == ConsoleKey.F1) { Console.WriteLine("F1"); } if (key.Key == ConsoleKey.Backspace) { if (input.Count > 0) { input.RemoveAt(input.Count - 1); Console.Write(key.KeyChar); } }else if (key.Key == ConsoleKey.Escape){ Console.Clear(); Console.WriteLine("Input: {0}\n\n",new String(input.ToArray())); input.Clear(); }else if (key.Key >= ConsoleKey.A && key.Key <= ConsoleKey.Z){ input.Add(key.KeyChar); Console.Write(key.KeyChar); } } while (key.Key != ConsoleKey.X || key.Modifiers != ConsoleModifiers.Alt); } }
10 ConsoleKeyInfo.Modifiers
using System; using System.Collections.Generic; class MainClass { public static void Main() { ConsoleKeyInfo key; List<char> input = new List<char>(); do{ key = Console.ReadKey(true); if (key.Key == ConsoleKey.F1) { Console.WriteLine("F1"); } if (key.Key == ConsoleKey.Backspace) { if (input.Count > 0) { input.RemoveAt(input.Count - 1); Console.Write(key.KeyChar); } }else if (key.Key == ConsoleKey.Escape){ Console.Clear(); Console.WriteLine("Input: {0}\n\n",new String(input.ToArray())); input.Clear(); }else if (key.Key >= ConsoleKey.A && key.Key <= ConsoleKey.Z){ input.Add(key.KeyChar); Console.Write(key.KeyChar); } } while (key.Key != ConsoleKey.X || key.Modifiers != ConsoleModifiers.Alt); } }
11 ConsoleKeyInfo.KeyChar
using System; class MainClass { public static void Main() { ConsoleKeyInfo keypress; Console.WriteLine("Enter keystrokes. Enter Q to stop."); do { keypress = Console.ReadKey(); // read keystrokes Console.WriteLine(" Your key is: " + keypress.KeyChar); // Check for modifier keys. if((ConsoleModifiers.Alt & keypress.Modifiers) != 0) Console.WriteLine("Alt key pressed."); if((ConsoleModifiers.Control & keypress.Modifiers) != 0) Console.WriteLine("Control key pressed."); if((ConsoleModifiers.Shift & keypress.Modifiers) != 0) Console.WriteLine("Shift key pressed."); } while(keypress.KeyChar != 'Q'); } }
12 Enum.Format()
using System; enum EmployeeType : byte { Manager = 10, Programmer = 1, Contractor = 100, Developer = 9 } class MainClass { public static void Main(string[] args) { EmployeeType fred; fred = EmployeeType.Developer; Console.WriteLine("You are a {0}", fred.ToString()); Console.WriteLine("Hex value is {0}", Enum.Format(typeof(EmployeeType), fred, "x")); Console.WriteLine("Int value is {0}", Enum.Format(typeof(EmployeeType), fred, "D")); } }
13 Enum.Parse
using System; enum Color { red, green, yellow } public class MainClass { public static void Main() { Color c = Color.red; // c = (Color) Enum.Parse(typeof(Color), "Red", true); Console.WriteLine("string value is: {0}", c); } }
14 Enum.IsDefined
using System; enum Color { red, green, yellow } public class MainClass { public static void Main() { bool defined = Enum.IsDefined(typeof(Color), 5); Console.WriteLine("5 is a defined value for Color: {0}", defined); } }
15 Enum.GetUnderlyingType()
using System; enum EmployeeType : byte { Manager = 10, Programmer = 1, Contractor = 100, Developer = 9 } class MainClass { public static void Main(string[] args) { Console.WriteLine(Enum.GetUnderlyingType(typeof(EmployeeType))); } }
16 Enum.GetNames
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; public class Form1 : Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox lstAlignmentH; private System.Windows.Forms.ComboBox lstTrimming; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox lstAlignmentV; public Form1() { InitializeComponent(); ResizeRedraw = true; lstAlignmentH.DataSource = Enum.GetNames(typeof(StringAlignment)); lstAlignmentV.DataSource = Enum.GetNames(typeof(StringAlignment)); lstTrimming.DataSource = Enum.GetNames(typeof(StringTrimming)); } private void TextWrap_Paint(object sender, PaintEventArgs e) { string text = "Alignment Alignment Alignment Alignment Alignment Alignment Alignment Alignment Alignment Alignment Alignment Alignment Alignment Alignment Alignment Alignment Alignment Alignment Alignment Center each line of text.Center each line of textCenter each line of textCenter each line of textCenter each line of textCenter each line of text"; StringFormat stringFormat = new StringFormat(); stringFormat.Alignment = (StringAlignment)Enum.Parse(typeof(StringAlignment), lstAlignmentH.Text); stringFormat.LineAlignment = (StringAlignment)Enum.Parse(typeof(StringAlignment), lstAlignmentV.Text); stringFormat.Trimming = (StringTrimming)Enum.Parse(typeof(StringTrimming), lstTrimming.Text); Font font = new Font("Verdana", 12); Rectangle rect = new Rectangle(30, 110, Width - 60, Height - 160); e.Graphics.DrawString(text, font, Brushes.Black, rect, stringFormat); Pen pen = Pens.Black; e.Graphics.DrawRectangle(pen, rect); } private void lst_Changed(object sender, EventArgs e) { Invalidate(); } private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.lstAlignmentH = new System.Windows.Forms.ComboBox(); this.lstTrimming = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.lstAlignmentV = new System.Windows.Forms.ComboBox(); this.SuspendLayout(); this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 19); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(113, 13); this.label1.TabIndex = 0; this.label1.Text = "Alignment (Horizontal):"; this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(12, 74); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(49, 13); this.label2.TabIndex = 1; this.label2.Text = "Trimming:"; this.lstAlignmentH.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.lstAlignmentH.FormattingEnabled = true; this.lstAlignmentH.Location = new System.Drawing.Point(131, 16); this.lstAlignmentH.Name = "lstAlignmentH"; this.lstAlignmentH.Size = new System.Drawing.Size(121, 21); this.lstAlignmentH.TabIndex = 2; this.lstAlignmentH.SelectedIndexChanged += new System.EventHandler(this.lst_Changed); this.lstTrimming.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.lstTrimming.FormattingEnabled = true; this.lstTrimming.Location = new System.Drawing.Point(131, 69); this.lstTrimming.Name = "lstTrimming"; this.lstTrimming.Size = new System.Drawing.Size(121, 21); this.lstTrimming.TabIndex = 3; this.lstTrimming.SelectedIndexChanged += new System.EventHandler(this.lst_Changed); this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(12, 47); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(100, 13); this.label3.TabIndex = 4; this.label3.Text = "Alignment (Vertical):"; this.lstAlignmentV.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.lstAlignmentV.FormattingEnabled = true; this.lstAlignmentV.Location = new System.Drawing.Point(131, 42); this.lstAlignmentV.Name = "lstAlignmentV"; this.lstAlignmentV.Size = new System.Drawing.Size(121, 21); this.lstAlignmentV.TabIndex = 5; this.lstAlignmentV.SelectedIndexChanged += new System.EventHandler(this.lst_Changed); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(319, 296); this.Controls.Add(this.lstAlignmentV); this.Controls.Add(this.label3); this.Controls.Add(this.lstTrimming); this.Controls.Add(this.lstAlignmentH); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Name = "TextWrap"; this.Text = "Text Wrap"; this.Paint += new System.Windows.Forms.PaintEventHandler(this.TextWrap_Paint); this.ResumeLayout(false); this.PerformLayout(); } [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new Form1()); } }
17 extends EventArgs
using System; public class UIEvent : EventArgs { public UIEvent( string filename ) { this.filename = filename; } private string filename; public string Filename { get { return filename; } } } public class MyUI { public event EventHandler<UIEvent> PlayEvent; public void UserPressedPlay() { OnPlay(); } protected virtual void OnPlay() { EventHandler<UIEvent> localHandler = PlayEvent; if( localHandler != null ) { localHandler( this, new UIEvent("somefile.wav") ); } } } public class MainClass { public static void Main() { MyUI ui = new MyUI(); ui.PlayEvent += PlaySomething; } private static void PlaySomething( object source, UIEvent args ) { Console.WriteLine("Play the file"); } }
18 extends Exception
using System; using System.Runtime.Serialization; [Serializable] public sealed class MyException : Exception { private string stringInfo; private bool booleanInfo; public MyException() : base() { } public MyException(string message) : base(message) { } public MyException(string message, Exception inner): base(message, inner) { } private MyException(SerializationInfo info, StreamingContext context) : base(info, context) { stringInfo = info.GetString("StringInfo"); booleanInfo = info.GetBoolean("BooleanInfo"); } public MyException(string message, string stringInfo, bool booleanInfo) : this(message) { this.stringInfo = stringInfo; this.booleanInfo = booleanInfo; } public MyException(string message, Exception inner, string stringInfo, bool booleanInfo): this(message, inner) { this.stringInfo = stringInfo; this.booleanInfo = booleanInfo; } public string StringInfo { get { return stringInfo; } } public bool BooleanInfo { get { return booleanInfo; } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("StringInfo", stringInfo); info.AddValue("BooleanInfo", booleanInfo); base.GetObjectData(info, context); } public override string Message { get { string message = base.Message; if (stringInfo != null) { message += Environment.NewLine + stringInfo + " = " + booleanInfo; } return message; } } } public class MainClass { public static void Main() { try { throw new MyException("Some error", "SomeCustomMessage", true); } catch (MyException ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.BooleanInfo); Console.WriteLine(ex.StringInfo); } } }
19 Exception.TargetSite
using System; class MainClass { public static void Main() { try { int[] nums = new int[4]; Console.WriteLine("Before exception is generated."); // Generate an index out-of-bounds exception. for(int i=0; i < 10; i++) { nums[i] = i; } } catch (IndexOutOfRangeException exc) { Console.WriteLine("Standard message is: "); Console.WriteLine(exc); // calls ToString() Console.WriteLine("Stack trace: " + exc.StackTrace); Console.WriteLine("Message: " + exc.Message); Console.WriteLine("TargetSite: " + exc.TargetSite); Console.WriteLine("Class defining member: {0}", exc.TargetSite.DeclaringType); Console.WriteLine("Member type: {0}", exc.TargetSite.MemberType); Console.WriteLine("Source: {0}", exc.Source); Console.WriteLine("Help Link: {0}", exc.HelpLink); } Console.WriteLine("After catch statement."); } }
20 Exception.Source
using System; class MainClass { public static void Main() { try { int[] nums = new int[4]; Console.WriteLine("Before exception is generated."); // Generate an index out-of-bounds exception. for(int i=0; i < 10; i++) { nums[i] = i; } } catch (IndexOutOfRangeException exc) { Console.WriteLine("Standard message is: "); Console.WriteLine(exc); // calls ToString() Console.WriteLine("Stack trace: " + exc.StackTrace); Console.WriteLine("Message: " + exc.Message); Console.WriteLine("TargetSite: " + exc.TargetSite); Console.WriteLine("Class defining member: {0}", exc.TargetSite.DeclaringType); Console.WriteLine("Member type: {0}", exc.TargetSite.MemberType); Console.WriteLine("Source: {0}", exc.Source); Console.WriteLine("Help Link: {0}", exc.HelpLink); } Console.WriteLine("After catch statement."); } }
21 Exception.HelpLink
using System; class MainClass { public static void Main() { try { int[] nums = new int[4]; Console.WriteLine("Before exception is generated."); // Generate an index out-of-bounds exception. for(int i=0; i < 10; i++) { nums[i] = i; } } catch (IndexOutOfRangeException exc) { Console.WriteLine("Standard message is: "); Console.WriteLine(exc); // calls ToString() Console.WriteLine("Stack trace: " + exc.StackTrace); Console.WriteLine("Message: " + exc.Message); Console.WriteLine("TargetSite: " + exc.TargetSite); Console.WriteLine("Class defining member: {0}", exc.TargetSite.DeclaringType); Console.WriteLine("Member type: {0}", exc.TargetSite.MemberType); Console.WriteLine("Source: {0}", exc.Source); Console.WriteLine("Help Link: {0}", exc.HelpLink); } Console.WriteLine("After catch statement."); } }
22 GC.AddMemoryPressure
using System; using System.IO; using System.Reflection; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; public class MainClass { public static void Main() { IntPtr ptr = Marshal.AllocHGlobal(1024); GC.AddMemoryPressure(1024); if (ptr != IntPtr.Zero) { Marshal.FreeHGlobal(ptr); ptr = IntPtr.Zero; GC.RemoveMemoryPressure(1024); } } }
23 GC.RemoveMemoryPressure
using System; using System.IO; using System.Reflection; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; public class MainClass { public static void Main() { IntPtr ptr = Marshal.AllocHGlobal(1024); GC.AddMemoryPressure(1024); if (ptr != IntPtr.Zero) { Marshal.FreeHGlobal(ptr); ptr = IntPtr.Zero; GC.RemoveMemoryPressure(1024); } } }
24 GC.MaxGeneration
using System; using System.Collections.Generic; using System.Text; class Program { static void Main(string[] args) { Console.WriteLine("Estimated bytes on heap: {0}", GC.GetTotalMemory(false)); Console.WriteLine("This OS has {0} object generations.\n", (GC.MaxGeneration + 1)); } }
25 GC.GetTotalMemory
using System; using System.Collections.Generic; using System.Text; class Program { static void Main(string[] args) { Console.WriteLine("Estimated bytes on heap: {0}", GC.GetTotalMemory(false)); Console.WriteLine("This OS has {0} object generations.\n", (GC.MaxGeneration + 1)); } }
26 GC.GetGeneration
using System; using System.Collections.Generic; using System.Text; public class Car { private int currSp; private string petName; public Car() { } public Car(string name, int speed) { petName = name; currSp = speed; } public override string ToString() { return string.Format("{0} is going {1} MPH", petName, currSp); } } class Program { static void Main(string[] args) { Console.WriteLine("Estimated bytes on heap: {0}", GC.GetTotalMemory(false)); Console.WriteLine("This OS has {0} object generations.\n", (GC.MaxGeneration + 1)); Car refToMyCar = new Car("Zippy", 100); Console.WriteLine(refToMyCar.ToString()); Console.WriteLine("\nGeneration of refToMyCar is: {0}", GC.GetGeneration(refToMyCar)); } public static void MakeACar() { Car myCar = new Car(); } }
27 IADs.Get
using System; using System.Runtime.InteropServices; using System.DirectoryServices; using ActiveDs; public unsafe class MainClass { public static int Main(string[] args) { string Path = "LDAP://dsaddom.nttest.microsoft.com/rootDSE"; IADs pIADs = null; DirectoryEntry Entry = new DirectoryEntry(Path); pIADs = (IADs)Entry.NativeObject; string DefaultNamingContext = (string)pIADs.Get("defaultNamingContext"); Console.WriteLine(DefaultNamingContext); Array NamingContext = (Array)pIADs.GetEx("defaultNamingContext"); for(int i = 0; i < NamingContext.GetLength(0); i++) { Console.WriteLine((string)NamingContext.GetValue(i)); } return 0; } }
28 IADs.GetEx
using System; using System.Runtime.InteropServices; using System.DirectoryServices; using ActiveDs; public unsafe class MainClass { public static int Main(string[] args) { string Path = "LDAP://dsaddom.nttest.microsoft.com/rootDSE"; IADs pIADs = null; DirectoryEntry Entry = new DirectoryEntry(Path); pIADs = (IADs)Entry.NativeObject; Array NamingContexts = (Array)pIADs.Get("namingContexts"); for(int i = 0; i < NamingContexts.GetLength(0); i++) { Console.WriteLine((string)NamingContexts.GetValue(i)); } Array Contexts = (Array)pIADs.GetEx("namingContexts"); for(int i = 0; i < NamingContexts.GetLength(0); i++) { Console.WriteLine((string)Contexts.GetValue(i)); } return 0; } }
29 implements ICloneable
using System; class MyValue { public MyValue(int count) { this.count = count; } public int count; } class MyObject: ICloneable { public MyObject(int count) { this.contained = new MyValue(count); } public object Clone() { Console.WriteLine("Clone"); return(new MyObject(this.contained.count)); } public MyValue contained; } class MainClass { public static void Main() { MyObject my = new MyObject(33); MyObject myClone = (MyObject) my.Clone(); Console.WriteLine("Values: {0} {1}", my.contained.count, myClone.contained.count); myClone.contained.count = 15; Console.WriteLine("Values: {0} {1}", my.contained.count, myClone.contained.count); } }
30 implements ICustomFormatter
using System; using System.Text; using System.Globalization; public class WordyFormatProvider : IFormatProvider, ICustomFormatter { static readonly string[] _numberWords = "zero one two three four five six seven eight nine minus point".Split(); IFormatProvider _parent; public WordyFormatProvider() : this(CultureInfo.CurrentCulture) { } public WordyFormatProvider(IFormatProvider parent) { _parent = parent; } public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) return this; return null; } public string Format(string format, object arg, IFormatProvider prov) { if (arg == null || format != "W") return string.Format(_parent, "{0:" + format + "}", arg); StringBuilder result = new StringBuilder(); string digitList = string.Format(CultureInfo.InvariantCulture, "{0}", arg); foreach (char digit in digitList) { int i = "0123456789-.".IndexOf(digit); if (i == -1) continue; if (result.Length > 0) result.Append(' '); result.Append(_numberWords[i]); } return result.ToString(); } } public class MainClass { public static void Main() { double n = -123.45; IFormatProvider fp = new WordyFormatProvider(); Console.WriteLine(string.Format(fp, "{0:C} in words is {0:W}", n)); } }
31 implements IEquatable
using System; public struct Complex : IComparable, IEquatable<Complex>, IComparable<Complex>{ public Complex( double real, double img ) { this.real = real; this.img = img; } public override bool Equals( object other ) { bool result = false; if( other is Complex ) { result = Equals( (Complex) other ); } return result; } public bool Equals( Complex that ) { return (this.real == that.real && this.img == that.img); } public override int GetHashCode() { return (int) this.Magnitude; } public int CompareTo( Complex that ) { int result; if( Equals( that ) ) { result = 0; } else if( this.Magnitude > that.Magnitude ) { result = 1; } else { result = -1; } return result; } int IComparable.CompareTo( object other ) { if( !(other is Complex) ) { throw new ArgumentException( "Bad Comparison" ); } return CompareTo( (Complex) other ); } public override string ToString() { return String.Format( "({0}, {1})", real, img ); } public double Magnitude { get { return Math.Sqrt( Math.Pow(this.real, 2) + Math.Pow(this.img, 2) ); } } public static bool operator==( Complex lhs, Complex rhs ) { return lhs.Equals( rhs ); } public static bool operator!=( Complex lhs, Complex rhs ) { return !lhs.Equals( rhs ); } public static bool operator<( Complex lhs, Complex rhs ) { return lhs.CompareTo( rhs ) < 0; } public static bool operator>( Complex lhs, Complex rhs ) { return lhs.CompareTo( rhs ) > 0; } public static bool operator<=( Complex lhs, Complex rhs ) { return lhs.CompareTo( rhs ) <= 0; } public static bool operator>=( Complex lhs, Complex rhs ) { return lhs.CompareTo( rhs ) >= 0; } private double real; private double img; } public class MainClass { static void Main() { Complex cpx1 = new Complex( 1.0, 3.0 ); Complex cpx2 = new Complex( 1.0, 2.0 ); Console.WriteLine( "cpx1 = {0}, cpx1.Magnitude = {1}", cpx1, cpx1.Magnitude ); Console.WriteLine( "cpx2 = {0}, cpx2.Magnitude = {1}\n", cpx2, cpx2.Magnitude ); Console.WriteLine( "cpx1 == cpx2 ? {0}", cpx1 == cpx2 ); Console.WriteLine( "cpx1 != cpx2 ? {0}", cpx1 != cpx2 ); Console.WriteLine( "cpx1 < cpx2 ? {0}", cpx1 < cpx2 ); Console.WriteLine( "cpx1 > cpx2 ? {0}", cpx1 > cpx2 ); Console.WriteLine( "cpx1 <= cpx2 ? {0}", cpx1 <= cpx2 ); Console.WriteLine( "cpx1 >= cpx2 ? {0}", cpx1 >= cpx2 ); } }
32 IndexOutOfRangeException.Message
using System; public class Example10_2 { public static void Main() { try { int[] intArray = new int[5]; for (int counter = 0; counter <= intArray.Length; counter++) { intArray[counter] = counter; Console.WriteLine("intArray[" + counter + "] = " + intArray[counter]); } } catch (IndexOutOfRangeException e) { Console.WriteLine("IndexOutOfRangeException occurred"); Console.WriteLine("Message = " + e.Message); Console.WriteLine("Stack trace = " + e.StackTrace); } } }
33 new IntPtr
using System; using System.IO; using System.Reflection; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; public class MainClass { public unsafe static void Main() { int a = 10; Console.WriteLine("a is {0} ({0:X})", a); IntPtr ip = new IntPtr(&a); byte* pTarget = (byte*)ip.ToPointer() + 1; *pTarget = 2; Console.WriteLine("a is {0} ({0:X})", a); } }
34 Obsolete(String name)
using System; public class TestAno1 { [Obsolete("Use myMeth2, instead.")] static int myMeth(int a, int b) { return a / b; } // Improved version of myMeth. static int myMeth2(int a, int b) { return b == 0 ? 0 : a /b; } public static void Main() { Console.WriteLine("4 / 3 is " + TestAno1.myMeth(4, 3)); Console.WriteLine("4 / 3 is " + TestAno1.myMeth2(4, 3)); } }
35 SByte.MaxValue
using System; using System.Data; class Class1{ static void Main(string[] args){ uint x = 0x01001001; uint XComp = ~x; Console.WriteLine("~x = " + ~x); sbyte B1 = sbyte.MinValue; sbyte B2 = sbyte.MaxValue; Console.WriteLine("B1|B2 = " + (((byte)B1|(byte)B2))); ushort x2 = 0x00000001; // Problem Console.WriteLine("~x2 = " + ~x2); byte y = 1; // Problem //byte B = ~y; Console.WriteLine("~y = " + ~y); char x3 = (char)1; // Problem Console.WriteLine("~x3 = " + ~x3); sbyte x5 = 1; Console.WriteLine("~x5 = " + ~x5); uint IntResult = (uint)~x; Console.WriteLine("IntResult = " + IntResult); byte ByteResult = (byte)~y; Console.WriteLine("ByteResult = " + ByteResult); } }
36 SByte.MinValue
using System; using System.Data; class Class1{ static void Main(string[] args){ uint x = 0x01001001; uint XComp = ~x; Console.WriteLine("~x = " + ~x); sbyte B1 = sbyte.MinValue; sbyte B2 = sbyte.MaxValue; Console.WriteLine("B1|B2 = " + (((byte)B1|(byte)B2))); ushort x2 = 0x00000001; // Problem Console.WriteLine("~x2 = " + ~x2); byte y = 1; // Problem //byte B = ~y; Console.WriteLine("~y = " + ~y); char x3 = (char)1; // Problem Console.WriteLine("~x3 = " + ~x3); sbyte x5 = 1; Console.WriteLine("~x5 = " + ~x5); uint IntResult = (uint)~x; Console.WriteLine("IntResult = " + IntResult); byte ByteResult = (byte)~y; Console.WriteLine("ByteResult = " + ByteResult); } }
37 StackOverflowException.Message
using System; class MainClass { public static void Main() { try { Recursive(); } catch(StackOverflowException) { Console.WriteLine("The CLR is out of stack space."); } } public static void Recursive() { Recursive(); } }
38 new Timer()
using System; using System.Drawing; using System.Drawing.Text; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; public class FontForm : System.Windows.Forms.Form { private Timer timer; private int swellValue; private string fontFace = "WingDings"; public FontForm() { InitializeComponent(); timer = new Timer(); Text = "Font App"; Width = 425; Height = 150; BackColor = Color.Honeydew; CenterToScreen(); timer.Enabled = true; timer.Interval = 100; timer.Tick += new EventHandler(FontForm_OnTimer); } private void InitializeComponent() { this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 253); this.Text = "Form1"; this.Resize += new System.EventHandler(this.FontForm_Resize); this.Paint += new System.Windows.Forms.PaintEventHandler(this.FontForm_Paint); } static void Main() { Application.Run(new FontForm()); } private void FontForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; Font theFont = new Font(fontFace, 12 + swellValue); string message = "www.java2s.com"; float windowCenter = this.DisplayRectangle.Width / 2; SizeF stringSize = e.Graphics.MeasureString(message, theFont); float startPos = windowCenter - (stringSize.Width / 2); g.DrawString(message, theFont, new SolidBrush(Color.Blue), startPos, 10); } private void FontForm_Resize(object sender, System.EventArgs e) { Rectangle myRect = new Rectangle(0, 100, ClientRectangle.Width, ClientRectangle.Height); Invalidate(myRect); } private void FontForm_OnTimer(object sender, EventArgs e) { swellValue += 5; if(swellValue >= 50) swellValue = 0; Invalidate(new Rectangle(0, 0, ClientRectangle.Width, 100)); } }
39 UInt16.GetType()
using System; class MainClass { public static void Main(string[] args) { System.UInt16 myUInt16 = 30000; Console.WriteLine("Your value is: {0}", myUInt16.ToString()); Console.WriteLine("I am a: {0}", myUInt16.GetType().ToString()); } }
40 UInt16.ToString()
using System; class MainClass { public static void Main(string[] args) { System.UInt16 myUInt16 = 30000; Console.WriteLine("Your value is: {0}", myUInt16.ToString()); Console.WriteLine("I am a: {0}", myUInt16.GetType().ToString()); } }
41 UInt16.MinValue
using System; class MainClass { public static void Main(string[] args) { Console.WriteLine("Max for an UInt16 is: {0}", UInt16.MaxValue); Console.WriteLine("Min for an UInt16 is: {0}", UInt16.MinValue); } }
42 UInt16.MaxValue
using System; class MainClass { public static void Main(string[] args) { Console.WriteLine("Max for an UInt16 is: {0}", UInt16.MaxValue); Console.WriteLine("Min for an UInt16 is: {0}", UInt16.MinValue); } }
43 Version.Major
using System; using System.Reflection; [assembly:AssemblyVersionAttribute("1.2.3.4")] [assembly:AssemblyTitleAttribute("Example")] class MainClass { public static void Main() { Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; Console.WriteLine(v.ToString()); Console.WriteLine(v.Major + "." + v.Minor + "." + v.Build + "." + v.Revision); } }