Custom datatyper i C#
Hej,Jeg vil gerne oprette mine egne datatyper i c#.
Jvf. nedenstående link skulle det være nemt nok.
http://vbcity.com/blogs/jatkinson/archive/2010/01/12/create-custom-types-and-initialize-them-without-the-new-keyword-c-vb-net.aspx
Men det virker ikke. Jeg får følgende fejl:
A field initializer cannot reference the non-static field, method, or property 'WindowsFormsApplication1.minklasse.anotherAngle'
Hvad gør jeg galt ?
Mvh Ole
Her er min kode:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
struct Angle
{
// Private constructor called by [implicit operator Angle(...)]
private Angle(double value)
{
// Limiting an angle to the values between -360 and 360 degrees.
if (value < 360 && value > -360)
{
this._angle = value;
}
else
{
throw new ArgumentOutOfRangeException("value", "variable value must be between -360 and 360 degrees.");
}
}
// Holds an internal value of the angle.
private double _angle;
// Here we can initialize a new "Angle" without a constructor.
public static implicit operator Angle(double value)
{
return new Angle(value);
}
// Define the "+" behavior.
public static Angle operator +(Angle a1, Angle a2)
{
double temp = a1._angle + a2._angle;
// Check to see if the addition of two angles is too large
// to fit in out Angle data type.
if (temp < 360 && temp > -360)
{
return new Angle(temp);
}
else
{
throw new ArithmeticException();
}
}
// Define "-" behavior.
public static Angle operator -(Angle a1, Angle a2)
{
return new Angle(a1._angle - a2._angle);
}
// Type conversions
// Angle myAngle = 123.45;
// double d = myAngle;
public static implicit operator double(Angle value)
{
return value._angle;
}
// Angle myAngle = 123.45;
// float f = (float)myAngle;
public static explicit operator float(Angle value)
{
return (float)value._angle;
}
// Angle myAngle = 123.45;
// int i = (int)myAngle;
public static explicit operator int(Angle value)
{
return (int)value._angle;
}
public override string ToString()
{
return _angle.ToString();
}
}
class minklasse
{
// Assignment - virker
Angle myAngle = 1.23;
Angle anotherAngle = 90.00;
// Math operations - ingen af disse virker...
Angle addedAngle = myAngle + anotherAngle;
Angle KopiAngle = myAngle;
Angle subtractAngle = myAngle - anotherAngle;
}
}