C#類型轉(zhuǎn)換器的實(shí)現(xiàn)淺析
C#類型轉(zhuǎn)換器的實(shí)現(xiàn)是如何的呢?具體的操作是什么呢?那么這里就向你介紹C#類型轉(zhuǎn)換器的實(shí)現(xiàn)需要重寫四個(gè)方法,下面我們來具體看看細(xì)節(jié)是如何操作的。
C#類型轉(zhuǎn)換器的實(shí)現(xiàn)所用重寫的方法:
◆CanConvertFrom()――根據(jù)類型參數(shù)進(jìn)行測(cè)試,判斷是否能從這個(gè)類型轉(zhuǎn)換成當(dāng)前類型,在本例中我們只提供轉(zhuǎn)換string和InstanceDescriptor類型的能力。
◆CanConvertTo()――根據(jù)類型參數(shù)進(jìn)行測(cè)試,判斷是否能從當(dāng)前類型轉(zhuǎn)換成指定的類型。
◆ConvertTo()――將參數(shù)value的值轉(zhuǎn)換為指定的類型。
◆ConvertFrom()――串換參數(shù)value,并返回但書類型的一個(gè)對(duì)象。
C#類型轉(zhuǎn)換器的實(shí)現(xiàn)實(shí)例:
- public override object ConvertTo(
- ITypeDescriptorContext context,
- System.Globalization.CultureInfo culture,
- object value, Type destinationType)
- {
- String result = "";
- if (destinationType == typeof(String))
- {
- Scope scope = (Scope)value;
- result = scope.Min.ToString()+"," + scope.Max.ToString();
- return result;
- }
- if (destinationType == typeof(InstanceDescriptor))
- {
- ConstructorInfo ci =
- typeof(Scope).GetConstructor(
- new Type[] {typeof(Int32),typeof(Int32) });
- Scope scope = (Scope)value;
- return new InstanceDescriptor(
- ci, new object[] { scope.Min,scope.Max });
- }
- return base.ConvertTo(context,
- culture, value, destinationType);
- }
上面是ConvertTo的實(shí)現(xiàn),如果轉(zhuǎn)換的目標(biāo)類型是string,我將Scope的兩個(gè)屬性轉(zhuǎn)換成string類型,并且用一個(gè)“,”連接起來,這就是我們?cè)趯傩詾g覽器里看到的表現(xiàn)形式,如圖:
如果轉(zhuǎn)換的目標(biāo)類型是實(shí)例描述器(InstanceDescriptor,它負(fù)責(zé)生成實(shí)例化的代碼),我們需要構(gòu)造一個(gè)實(shí)例描述器,構(gòu)造實(shí)例描述器的時(shí)候,我們要利用反射機(jī)制獲得Scope類的構(gòu)造器信息,并在new的時(shí)候傳入Scope實(shí)例的兩個(gè)屬性值。實(shí)例描述器會(huì)為我們生成這樣的代碼:this.myListControl1.Scope = new CustomControlSample.Scope(10, 200);在最后不要忘記調(diào)用 base.ConvertTo(context, culture, value, destinationType),你不需要處理的轉(zhuǎn)換類型,交給基類去做好了。
- public override object ConvertFrom(
- ITypeDescriptorContext context,
- System.Globalization.CultureInfo culture,
- object value)
- {
- if (value is string)
- {
- String[] v = ((String)value).Split(',');
- if (v.GetLength(0) != 2)
- {
- throw new ArgumentException(
- "Invalid parameter format");
- }
- Scope csf = new Scope();
- csf.Min = Convert.ToInt32(v[0]);
- csf.Max = Convert.ToInt32(v[1]);
- return csf;
- }
- return base.ConvertFrom(context, culture, value);
- }
- }
上面是ConvertFrom的代碼,由于系統(tǒng)能夠直接將實(shí)例描述器轉(zhuǎn)換為Scope類型,所以我們就沒有必要再寫代碼,我們只需要關(guān)注如何將String(在屬性瀏覽出現(xiàn)的屬性值的表達(dá))類型的值轉(zhuǎn)換為Scope類型。沒有很復(fù)雜的轉(zhuǎn)換,只是將這個(gè)字符串以“,”分拆開,并串換為Int32類型,然后new一個(gè)Scope類的實(shí)例,將分拆后轉(zhuǎn)換的兩個(gè)整型值賦給Scope的實(shí)例,然后返回實(shí)例。在這段代碼里,我們要判斷一下用戶設(shè)定的屬性值是否有效。比如,如果用戶在Scope屬性那里輸入了“10200”,由于沒有輸入“,”,我們無法將屬性的值分拆為兩個(gè)字符串,也就無法進(jìn)行下面的轉(zhuǎn)換,所以,我們要拋出一個(gè)異常,通知用戶重新輸入。
C#類型轉(zhuǎn)換器的實(shí)現(xiàn)的相關(guān)內(nèi)容就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C#類型轉(zhuǎn)換器的實(shí)現(xiàn)有所幫助。
【編輯推薦】