Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze the problem of type conversion in Nullable

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article analyzes "how to analyze the type conversion problem of Nullable". The content is detailed and easy to understand. Friends who are interested in "how to analyze the type conversion of Nullable" can follow the editor's train of thought to read it in depth. I hope it will be helpful to you after reading. Let's follow the editor to learn more about "how to analyze the type conversion problem of Nullable".

Let's discuss the conversion of nullable value types (Nullable), but exactly how to convert a type of value object to a corresponding nullable value.

1. Four typical types of conversion

For type conversions, or further, we have four typical conversions between native types such as Int, Double, DateTime, String, and so on. If there is no hermit conversion relationship storage between types, we can convert each other explicitly through type conversion operators, such as:

Double doubleValue = 3.14159265; int intValue = (int) doubleValue

The second is with the help of Convert, a static type of ChangeType or ToXxx method (Xxx represents the target type of the transformation), such as:

String literalValue = "123"; int intValue1 = Convert.ToInt32 (literalValue); int intValue2 = (int) Convert.ChangeType (literalValue,typeof (int))

The third method is to create TypeConverter or several of its subclasses based on specific types, such as StringConverter, BooleanConverter, DateTimeConverter, and so on. When using it, you need to instantiate the corresponding TypeConverter first, and then call the appropriate type conversion method. For example:

String literalValue = "1981-08-24"; DateTimeConverter dateTypeConverter = newDateTimeConverter (); DateTime dateTimeValue = (DateTime) dateTypeConverter.ConvertFromString (literalValue); literalValue = "02:40:50"; TimeSpanConverter timeSpanConverter = new imeSpanConverter (); TimeSpan timeSpanValue = (TimeSpan imeSpanConverter.ConvertFromString (literalValue))

* A common method is to convert a formatted string based on a specific type into a corresponding type. We can call a specific type of static method Parse or TryParse to achieve type conversion, such as:

String literalValue = "1981-08-24"; DateTime dateTimeValue1 = DateTime.Parse (literalValue); DateTime dateTimeValue2; if (DateTime.TryParse (literalValue, out dateTimeValue2)) {/ /.}

2. When type conversion encounters Nullable type

Convert implements the conversion between almost all "compatible types" and parses strings with legal formats like the Parse method. However, if the target type is changed to a Nullable type, the type conversion will fail. For example, let's change the target type of the second example above from int to int? (Nullable):

String literalValue = "123"; try {int? IntValue = (int?) Convert.ChangeType (literalValue,typeof (int));} catch (InvalidCastException ex) {Console.WriteLine (ex.Message);}

The type conversion error message is output:

Invalid cast from 'System.String' to' system. Nullable`1 [[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'

In fact, if you call Convert's ChangeType method to convert any type of object to a Nullable type, an InvalidCastException exception will be thrown, even if you convert the T type to Nullable. For example, let's change the Central Plains data type in the above example to int type:

Int intValue1 = 123; try {int? IntValue = (int?) Convert.ChangeType (intValue1,typeof (int));} catch (InvalidCastException ex) {Console.WriteLine (ex.Message);}

A similar error message will still be entered:

Invalid cast from 'System.Int32' to' system. Nullable`1 [[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.

In fact, T-type objects can be explicitly or implicitly converted to Nullable objects. That is, there is no problem with the type conversion represented by the following code:

Int intValue1 = 123; int? IntValue2 = intValue1; int? IntValue3 = (int?) intValue1

Third, implement the type conversion based on Nullable in the extension method.

From the above introduction, we can draw the conclusion that if types T1 and T2 are compatible, we can convert T1 type objects to T2 types with Convert, and then further convert them to Nullable through explicit type conversion. We can use these two steps to achieve the conversion for Nullable types. For ease of operation, I wrote this transformation logic in an extension method for the IConvertible interface:

Public static class ConvertionExtensions {public static T? ConvertTo (this IConvertible convertibleValue) where T: struct {if (null = = convertibleValue) {return null;} return (T?) Convert.ChangeType (convertibleValue, typeof (T);}}

With the above extension method ConvertTo, it is easy to convert the target type to Nullable:

Int? IntValue = "123" .ConvertTo (); double? DoubleValue = "123" .ConvertTo (); DateTime? DateTimeValue = "1981-08-24" .ConvertTo ()

Fourth, further improve the extension method ConvertTo

The extension method defined above can only complete the conversion for the target type Nullable. Now let's further refine it so that this method can implement the conversion between any type. Here is the definition of our new version of the ConvertTo method:

Public static T ConvertTo (this IConvertible convertibleValue) {if (null = = convertibleValue) {return default (T);} if (! typeof (T) .IsGenericType) {return (T) Convert.ChangeType (convertibleValue, typeof (T));} else {Type genericTypeDefinition = typeof (T). GetGenericTypeDefinition (); if (genericTypeDefinition = = typeof (Nullable)) {return (T) Convert.ChangeType (convertibleValue, Nullable.GetUnderlyingType (typeof (T) }} throw new InvalidCastException (string.Format ("Invalid cast from type\" {0}\ "to type\" {1}\ "., convertibleValue.GetType () .FullName, typeof (T) .FullName));}

In the above method, we first need to determine whether the target type is Nullable, which can be determined by calling the GetGenericTypeDefinition method of the Type object. If so, first convert it to the corresponding base type (the generic type of Nullable). We can get this basic type (UnderlyingType) by calling the static method GetUnderlyingType of the static class Nullable. With this complete version of the ConvertTo extension method, we can do any type conversion-- regardless of whether the target type is a nullable type or a non-nullable type:

Int intValue1 = "123" .ConvertTo (); int? IntValue2 = "123" .ConvertTo (); DateTime dateTimeValue1 = "1981-08-24" .ConvertTo (); DateTime? DateTimeValue2 = "1981-08-24" .ConvertTo ()

Talk about NullableConverter

The above mentioned the type TypeConverter and said that it has a series of subclasses for specific data types. One of the subclasses is NullableConverter, so the name implies, this TypeConverter is used specifically for type conversion of Nullable. It is convenient to use this class to implement conversions for nullable types, such as:

String literalValue = "1981-08-24"; NullableConverter converter = new NullableConverter (typeof (DateTime?)); DateTime? DateTimevalue = (DateTime?) converter.ConvertFromString (literalValue); this is the end of the question about how to analyze the type conversion of Nullable. I hope the above content will improve everyone. If you want to learn more knowledge, please pay more attention to the editor's updates. Thank you for following the website!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report