新聞中心
本篇文章討論可空值類型(Nullable

十多年的東西湖網(wǎng)站建設(shè)經(jīng)驗(yàn),針對(duì)設(shè)計(jì)、前端、開發(fā)、售后、文案、推廣等六對(duì)一服務(wù),響應(yīng)快,48小時(shí)及時(shí)工作處理。全網(wǎng)營(yíng)銷推廣的優(yōu)勢(shì)是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動(dòng)調(diào)整東西湖建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計(jì),從而大程度地提升瀏覽體驗(yàn)。成都創(chuàng)新互聯(lián)公司從事“東西湖網(wǎng)站設(shè)計(jì)”,“東西湖網(wǎng)站推廣”以來,每個(gè)客戶項(xiàng)目都認(rèn)真落實(shí)執(zhí)行。
一、四種典型的類型轉(zhuǎn)換方式
對(duì)于類型轉(zhuǎn)化,或者進(jìn)一步地,對(duì)于像Int、Double、DateTime、String等這些原生類型之間的轉(zhuǎn)化,我們具有四種典型的轉(zhuǎn)換方式。如果類型之間不具有隱士轉(zhuǎn)換關(guān)系存儲(chǔ),我們可以之間通過類型轉(zhuǎn)換操作符進(jìn)行顯式轉(zhuǎn)換,比如:
- double doubleValue = 3.14159265;
- int intValue = (int)doubleValue;
第二種則是借助于Convert這個(gè)靜態(tài)類型的ChangeType或者ToXxx方法(Xxx代表轉(zhuǎn)換的目標(biāo)類型),比如:
- string literalValue = "123";
- int intValue1 = Convert.ToInt32(literalValue);
- int intValue2 = (int)Convert.ChangeType(literalValue,typeof(int));
第三種方法為創(chuàng)建TypeConverter或者它的基于具體類型的若干子類,比如StringConverter、BooleanConverter、DateTimeConverter等。在使用的時(shí)候你需要先實(shí)例化相應(yīng)的TypeConverter,然后調(diào)用相應(yīng)的類型轉(zhuǎn)換方法。比如:
- 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);
***一種常見的方法用在將基于某種具體類型的格式化字符串轉(zhuǎn)化成對(duì)應(yīng)的類型,我們可以調(diào)用具體類型的靜態(tài)方法Parse或者TryParse實(shí)現(xiàn)類型的轉(zhuǎn)換,比如:
- string literalValue = "1981-08-24";
- DateTime dateTimeValue1 = DateTime.Parse(literalValue); DateTime dateTimeValue2;
- if (DateTime.TryParse(literalValue, out dateTimeValue2))
- {
- //...
- }
二、當(dāng)類型轉(zhuǎn)換遭遇Nullable
Convert幾乎實(shí)現(xiàn)所有“兼容類型”之間的轉(zhuǎn)換,也可以向Parse方法一樣解析具有合法格式的字符串。但是,如果目標(biāo)類型換成是Nullable
- string literalValue = "123";
- try
- {
- int? intValue = (int?)Convert.ChangeType(literalValue,typeof(int?));
- }
- catch (InvalidCastException ex)
- {
- Console.WriteLine(ex.Message);
- }
類型轉(zhuǎn)換錯(cuò)誤消息會(huì)被輸出:
- Invalid cast from 'System.String' to 'System.Nullable`1[[System.Int32, mscorlib,
- Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'
實(shí)際上,如果你調(diào)用Convert的ChangeType方法將任何類型對(duì)象轉(zhuǎn)換成Nullable
- int intValue1 = 123;
- try
- {
- int? intValue = (int?)Convert.ChangeType(intValue1,typeof(int?));
- }
- catch (InvalidCastException ex)
- {
- Console.WriteLine(ex.Message);
- }
依然會(huì)輸入類似的錯(cuò)誤信息:
- Invalid cast from 'System.Int32' to 'System.Nullable`1[[System.Int32, mscorlib,
- Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.
而實(shí)際上,T類型的對(duì)象是可以顯式或者隱式轉(zhuǎn)化成Nullable
- int intValue1 = 123;
- int? intValue2 = intValue1;
- int? intValue3 = (int?)intValue1;
三、將基于Nullable
從上面的介紹我們可以得出這樣的結(jié)論:如果類型T1和T2能夠相互兼容,我們可以借助Convert將T1類型對(duì)象轉(zhuǎn)換成T2類型,然后通過顯式類型轉(zhuǎn)換進(jìn)一步轉(zhuǎn)換成Nullable
- 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));
- }
- }
借助于上面這個(gè)擴(kuò)展方法ConvertTo,對(duì)于目標(biāo)類型為Nullable
- int? intValue = "123".ConvertTo
(); - double? doubleValue = "123".ConvertTo
(); - DateTime? dateTimeValue = "1981-08-24".ConvertTo
();
四、進(jìn)一步完善擴(kuò)展方法ConvertTo
上面定義的擴(kuò)展方法只能完成針對(duì)目標(biāo)類型為Nullable
- 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));
- }
在上面的方法中,我們首先需要確定目標(biāo)類型是否是Nullable
- int intValue1 = "123".ConvertTo
(); - int? intValue2 = "123".ConvertTo
(); - DateTime dateTimeValue1 = "1981-08-24".ConvertTo
(); - DateTime? dateTimeValue2 = "1981-08-24".ConvertTo
();
五、談?wù)凬ullableConverter
上面談到TypeConverter這個(gè)類型,并且說到它具有一系列針對(duì)具體數(shù)據(jù)類型的子類。其中一個(gè)子類就是NullableConverter,故名思義,這個(gè)TypeConverter專門用于Nullable
- string literalValue = "1981-08-24";
- NullableConverter converter = new NullableConverter(typeof(DateTime?));
- DateTime? dateTimevalue = (DateTime?)converter.ConvertFromString(literalValue);
文章名稱:談?wù)凬ullable的類型轉(zhuǎn)換問題
當(dāng)前鏈接:http://www.5511xx.com/article/djsidjd.html


咨詢
建站咨詢
