In the design software, there are sometimes conversions of meters and inches. Here we write these two types of implicit conversions.
Length type in meters // <summary>
/// Length in meters
/// </Summary>
Public class meterlength
{
Public float value {Get; set ;}
Public unittype unit {get {return unittype. meter ;}}
Public MeterLength (InchLength value)
{
Value = (float) (value. Value * 0.3048 );
}
Public MeterLength (float value)
{
Value = value;
}
Public override string ToString ()
{
Return Value. ToString (CultureInfo. InvariantCulture) + "" + Unit;
}
/// <Summary>
/// Meters are implicitly converted to inches.
/// </Summary>
/// <Param name = "value"> </param>
/// <Returns> </returns>
Public static implicit operator InchLength (MeterLength value)
{
Return new InchLength (value );
}
}
Length type in inches // <summary>
/// The length in inches
/// </Summary>
Public class inchlength
{
Public float value {Get; set ;}
Public unittype unit {get {return unittype. meter ;}}
Public inchlength (float value)
{
Value = value;
}
Public inchlength (meterlength value)
{
Value = (float) (value. Value/0.3048 );
}
Public override string tostring ()
{
Return Value. ToString (CultureInfo. InvariantCulture) + "" + Unit;
}
/// <Summary>
/// Inches are implicitly converted to meters.
/// </Summary>
/// <Param name = "value"> </param>
/// <Returns> </returns>
Public static implicit operator MeterLength (InchLength value)
{
Return new MeterLength (value );
}
}
Length unit type definition public class unittype
{
/// <Summary>
/// Length unit type: meters
/// </Summary>
Public static readonly unittype meter = new unittype () {name = "meter "};
/// <Summary>
/// Length unit type: inches
/// </Summary>
Public static readonly UnitType Inch = new UnitType () {Name = "Inch "};
Private UnitType (){}
Public string Name {get; private set ;}
/// <Summary>
/// International text display
/// </Summary>
Public string Text
{
Get
{
// International key
String key = this. GetType (). ToString () + "." + Name;
// The corresponding internationalized text should be returned based on the key here. Currently, the Name is returned if no internationalized processing is available.
Return Name;
}
}
Public override string tostring ()
{
Return text;
}
}
InchLength length = new MeterLength (1 );
MessageBox. Show (length. ToString ());
The purpose of this article is to tell everyone that apart from float a = (float) 0.111233;, different types of user-defined data can also be converted.