C Sharp Snippets

From no name for this wiki
Revision as of 09:23, 17 September 2016 by Claude (talk | contribs) (Enums)
Jump to: navigation, search

C# Coding Snippets

Mehrfachvererbung

In C# ist Mehrfach Vererbung mit Interfaces möglich. Dies ist dank einer in den Metadaten gespeicherten Relation möglich (Table 0x19, MethodImpl). Diese Relation verbindet die Methodenimplementationen mit den Interfaces.

Multithreading

C# 2.0

C# 3.0

Implicit types, var

 var variable = new int[] {2,3,4,5};

Lamda expressions

 public delegate int HelloDelegate(int x, int y);
 //...
 HelloDelegate helloDel = (int arg1, int arg2) => arg1 * arg2;
 int res = helloDel(4, 5);

Object initialization

 Bean myBean = new Bean(){
   Property1 = "Hugo";
   Property2 = 3;
 }

Anonymous types

 var x = new { Age = 4, Name = "Claude" };
 int age = x.Age;

LinQ

LINQ

yield

Demonstration vom yield statement. Restriktion: Keine ref oder out parameter. Weitere Einschränkungen, siehe C# Referenz.

private void button1_Click(object sender, EventArgs e)
{
  MyClass myClass = new MyClass();
  foreach (string myString in myClass)
  {
                //Do Something
  }
}

public class MyClass : System.Collections.IEnumerable
{

   System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
   {
     yield return "hello";
     yield return "world";
     yield return "autsch";
  }
}

Hier ein Sample mit dem Generics Interface (IEnumerable<string>)

public class MyClass : System.Collections.Generic.IEnumerable<string>
{

   System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
   {
      System.Collections.Generic.IEnumerable<string> enumerable = this;
      return enumerable.GetEnumerator();
   }


   System.Collections.Generic.IEnumerator<string> System.Collections.Generic.IEnumerable<string>.GetEnumerator()
   {
      yield return "hello";
      yield return "world";
      yield return "autsch";
   }
}

Text

String Builder

In C# ist der StringBuilder analog zu Javas StringBuffer,StringBuilder.

StringBuilder sb = new StringBuilder ();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");

Write, WriteLine

Console.WriteLine("{0} ist {1}","Pferd", "schwer");

Regular Expressions

Wichtiger Namespace ist System.Text.RegularExpressions. Testapplet: RETester Hello World:

 Regex regex = new Regex("Hello|World");
 MatchCollection mc = regex.Matches("Hello World");
 for (int i = 0; i < mc.Count; i++)
 {
  Console.WriteLine(mc[i].Value);                
 }

Ein weiteres Beispiel:

 private string evaluate(string pattern, string text)
 {
  Regex regex = new Regex(pattern);
  Match match = regex.Match(text);
  StringBuilder sb = new StringBuilder();
  while (match.Success)
  {
   sb.AppendLine("Match: " + match.Value);
   foreach (Group group in match.Groups)
   {
    sb.AppendLine(" Group: " + group.Value);
    foreach (Capture capture in group.Captures)
    {
     sb.AppendLine("  Capture:" + capture.Value);
    }
   }
   match = match.NextMatch();
  }
  return sb.ToString();
 }

Back references

Beispiel einer Backreferenz:

(?<mybackrefname>Hello)\k<mybackrefname>

Die obige regular Expression matcht z.B. HelloHello, aber nicht Hello.

Processes, WMI

List Processes

			foreach(System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses()){
				Console.WriteLine("{0},{1}", p.Id.ToString(), p.ProcessName);
				foreach(System.Diagnostics.ProcessModule pm in p.Modules ){
					Console.WriteLine("  modulename: {0}", pm.ModuleName);
				}
			}

WMI Sample

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            System.Management.ManagementScope scope = new System.Management.ManagementScope(@"\\localhost\root\cimv2");
            scope.Connect();
            ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection coll = searcher.Get();

            foreach (ManagementObject obj in coll)
            {
               sb.AppendLine(obj["csname"].ToString());

            }

            this.textBox.Text = sb.ToString();

WMI Sample 2, Listen to events

        ManagementEventWatcher watcher;

        private void button1_Click_1(object sender, EventArgs ex)
        {

            WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 2), "TargetInstance isa \"Win32_Process\"");
            watcher = new ManagementEventWatcher(query);
            watcher.EventArrived += new EventArrivedEventHandler(OnEventArrived);
            watcher.Start();
            this.textBox.Text =  "Started";
            
        }

        public void OnEventArrived(object sender, EventArrivedEventArgs e)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();           
            sb.AppendLine(DateTime.Now.ToString());
            ManagementBaseObject evt = e.NewEvent;
            ManagementBaseObject target = (ManagementBaseObject)evt["TargetInstance"];
            sb.AppendFormat("{0},{1}\n", target["Name"], target["ExecutablePath"]);
            string done = sb.ToString();
            handler h = () => this.textBox.Text = done;  //def of handler: delegate void handler();          
            this.Invoke(h);
           
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            this.watcher.Stop();
            this.textBox.Text = "Stopped";
        }

IO

Path

Der Path Separator (In Windows ist es ein Punktkomma oder Semmicolon) ist:

  Path.PathSeparator;

Der Directory Separator (In Windows ist es ein Backslash) ist:

 Path.DirectorySeparatorChar

Listen to the filesystem

Events werden ausgeloest, wenn sich der Verzeichnissinhalt aendert.

	class FileSystemWatcher
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("Hello World!");
			System.IO.FileSystemWatcher fsw = new System.IO.FileSystemWatcher("/home/claude");
			fsw.IncludeSubdirectories = false;
			fsw.EnableRaisingEvents = true;
			
			fsw.Changed += new System.IO.FileSystemEventHandler(FsChange);
			Console.ReadLine();
			Console.WriteLine("Exiting app ...");
			
		}
		
		public static void FsChange(object sender, System.IO.FileSystemEventArgs e){
			Console.WriteLine("Path:" + e.FullPath);
		}
	}

Environment variables

			IDictionary variables = Environment.GetEnvironmentVariables();
			foreach(System.Collections.DictionaryEntry item in variables){				
				Console.WriteLine(item.Key + ", " + item.Value);
			}

Operator Overloading

Binary Operators

    public class MySample
    {
        private int myInt = 0;

        public int Value {
            get
            {
                return this.myInt;
            }
            set
            {
                this.myInt = value;
            }
        }

        public static MySample operator +(MySample sample1, MySample sample2)
        {
            MySample result = new MySample();
            result.Value = sample1.Value + sample2.Value;
            return result;
        }
    }

Benutzen kann man den Binary Operator wie folgt:

MySample sample1 = new MySample();
MySample sample2 = new MySample();

sample1.Value = 3;
sample2.Value = 2;
MySample sample3  = sample1 + sample2;

Implicit Operators

MySample sample1 = new MySample();
MySample sample2 = new MySample();

sample1.Value = 3;
sample2.Value = 2;
MySample sample3  = sample1 + sample2;

int p = sample3; //Calling implicit operator
sample3 = 88; //Calling implicit operator

Implicit Operator:

    public class MySample
    {
        private int myInt = 0;

        public int Value {
            get
            {
                return this.myInt;
            }
            set
            {
                this.myInt = value;
            }
        }

        public static MySample operator +(MySample sample1, MySample sample2)
        {
            MySample result = new MySample();
            result.Value = sample1.Value + sample2.Value;
            return result;
        }

        public static implicit operator MySample(int value)
        {
            MySample result = new MySample();
            result.Value = value;
            return result;
        }

        public static implicit operator int(MySample value)
        {
            return value.Value;
        }

    }

Explicit operators

   public class Class1 { }
    public class Class2 { }

    public class Test { 
        public static void Sample(){
            ExplSample ex = new ExplSample();
            Class1 class1 = (Class1) ex;
            Class2 class2 = (Class2) ex;
        }
    }

    public class ExplSample
    {
        public static explicit operator Class1(ExplSample value)
        {
            return new Class1();
        }

        public static explicit operator Class2(ExplSample value)
        {
            return new Class2();
        }
        
    }

Enums

Enum definieren:

 public enum ClientType {Standard = 1, Silverlight = 2}

Enum konvertieren:

  ushort p = 1;
  ClientType x = (ClientType) p;
  ushort t = (ushort) x;

Bild manipulieren

Beispiel zum Manipulieren eines Bildes, ohne es auf dem Userinterface anzuzeigen.

 Bitmap image = new Bitmap(@"C:\tmp\myimage.jpg"); //Namespace System.Drawing
 Color newColor = Color.FromArgb(1, 2, 3); 
 Graphics g = Graphics.FromImage(image);
 g.Clear(Color.Red);
 image.SetPixel(x, y, newColor);
 image.Save(@"C:\tmp\myimage2.jpg");

Antialiasing

Kein Effekt auf Text, aber auf Polygone u.s.w.

 Graphics g = getGraphics();
 // Set the SmoothingMode property to smooth the line.
 g.SmoothingMode = 
 System.Drawing.Drawing2D.SmoothingMode.AntiAlias;