Spannende Cast-Implementierung in C#

by Bernhard Wurm 14. September 2010 08:32

Jeder der mit der Software Entwicklung beginnt lernt relativ schnell zwischen verschiedenen Datentypen umzuwandeln und zu casten. Von Object nach String. Von double zu int usw.

Doch wie wird eigentlich zwischen komplexeren Datentypen ein Cast durchgeführt?
Also von Duration nach Timespan? Von ServiceObject to BusinessEntity?
Als kleines Beispiel wär doch folgendes echt nett:

MyPoint p1 = new MyPoint();
p1.X = 10.1F;
p1.Y = 3.5F;
//Cast MyPoint to a string.
string pointInfo = (string)p1;

Oder noch viel schöner:

MyPoint p1 = new MyPoint();
p1.X = 10.1F;
p1.Y = 3.5F;
//Directly assign MyPoint object to a string.
string pointInfo1 = p1;

C# bietet hier tatsächlich entsprechende Operator-Implementierungen:
Für die implizite Implementierung

class MyPoint {
	public float X { get; set; }
	public float Y { get; set; }
	/// <summary>
	/// Allow the cast from a MyPoint object to a string. Allow an implicit cast!
	/// </summary>
	public static implicit operator string(MyPoint p) {
		return String.Format("{0};{1}", p.X, p.Y);
	}
	/// <summary>
	/// Cast from a string to a MyPoint-object
	/// </summary>
	public static implicit operator MyPoint(string s) {
		if (s == null)
			return null;
		if (s.IndexOf(';') == -1)
			return new MyPoint();
		//Get values
		float x = float.Parse(s.Split(';')[0]);
		float y = float.Parse(s.Split(';')[1]);
		return new MyPoint() { X = x, Y = y };
	}
}

Dadurch sind folgende Aufrufe möglich:

MyPoint p2 = "10.1;4";
string info = p2;

Eine feine Sache!
Tauscht man nun bei der operator-Implementierung das Wort “implicit” durch “explicit” sind explizite Casts möglich.

Comments

Austria on 9/14/2010 5:54:49 PM

wird bei uns auch verwendet. Beispielsweise für EventArgs<TData>. Anstatt EventArgs<TData> zu verwenden kann dann auch nur TData als Parameter verwendet werden bzw. kann TData dann auch EventArgs<TData> zugewiesen werden...

Bernhard Austria on 9/15/2010 1:37:12 PM

Feine Sache!

Yachtcharter Griechenland Greece on 10/26/2010 9:33:13 AM

This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free.

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading