Type Conversion
Convert type conversion and hexadecimal conversion tool.
Zongsoft.Common.Convert is an enhanced conversion tool within the framework covering regular type conversions, nullable types, enum aliases, TimeSpan Source abbreviation format, hex literals and custom converters.
Conversion Value
ConvertValue supports regular type conversion, enumeration alias conversion, TimeSpan Source abbreviation format conversion, and custom TypeConverter Source.
Source: framework/Zongsoft.Core/test/Common/ConvertTest.cs (excerpt; see source for context).
Assert.Null(Zongsoft.Common.Convert.ConvertValue<int?>("", default(int?)));
Assert.Null(Zongsoft.Common.Convert.ConvertValue<int?>("x", () => default(int?)));
Assert.NotNull(Zongsoft.Common.Convert.ConvertValue<int?>("123", () => default(int?)));
Assert.Equal(123, Zongsoft.Common.Convert.ConvertValue<int?>("123", () => default(int?)));
object value = 123;
Assert.Equal(123.0f, Zongsoft.Common.Convert.ConvertValue<float>(value));
Assert.Equal(123.0d, Zongsoft.Common.Convert.ConvertValue<double>(value));
Assert.Equal(123.0m, Zongsoft.Common.Convert.ConvertValue<decimal>(value));
value = "123";
Assert.Equal(123, Zongsoft.Common.Convert.ConvertValue<int>(value));TryConvertValue is suitable for scenarios where you do not want an exception to be thrown if the conversion fails. The following framework test also demonstrates the cooperation of the time span abbreviation format and type conversion.
Source: framework/Zongsoft.Core/test/Common/ConvertTest.cs (excerpt; see source for context).
Binary and hexadecimal text can be converted to and from each other.
Source: framework/Zongsoft.Core/test/Common/ConvertTest.cs (excerpt; see source for context).
Enum UtilitiesThese snippets come from the framework ConvertTest. BinaryCompare in the hex test is a helper method of the test class; the first two snippets are excerpts from inside the method. Discussions The actual implementation of custom tag conversion can be found at TagsConverter.
Related Resources
Last updated