2013-02-21 63 views
1

我正在使用一些第三方代碼,它使用TypeConverters將「對象」轉換爲指定爲通用參數的類型。TypeDescriptor.GetConverter(typeof(string))無法轉換爲我的自定義類型

第三方代碼獲取字符串類型轉換器,並希望通過該類型轉換器執行所有轉換。

var typeConverter = TypeDescriptor.GetConverter(typeof(string)); 

我寫了一個自定義類型和類型轉換器爲它(並與TypeDescriptor屬性註冊的話),但它沒有得到使用的第三方代碼,從而未能在調用typeConverter.CanConvertTo(MyCustomType)

直到今天,我只會在摘要中遇到TypeConverters,我已經看到他們提到但從未構建或使用過。

有沒有人知道我在做什麼錯在這裏?

我 - 削減 - 代碼

using System; 
using System.ComponentModel; 

namespace IoNoddy 
{ 
[TypeConverter(typeof(TypeConverterForMyCustomType))] 
public class MyCustomType 
{ 
    public Guid Guid { get; private set; } 
    public MyCustomType(Guid guid) 
    { 
     Guid = guid; 
    } 
    public static MyCustomType Parse(string value) 
    { 
     return new MyCustomType(Guid.Parse(value)); 
    } 
} 

public class TypeConverterForMyCustomType 
    : TypeConverter 
{ 
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) 
    { 
     return ((sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType)); 
    } 
    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) 
    { 
     string strValue; 
     if ((strValue = value as string) != null) 
      try 
      { 
       return MyCustomType.Parse(strValue); 
      } 
      catch (FormatException ex) 
      { 
       throw new FormatException(string.Format("ConvertInvalidPrimitive: Could not convert {0} to MyCustomType", value), ex); 
      } 
     return base.ConvertFrom(context, culture, value); 
    } 
} 
} 

static void Main(string[] args) 
{ 
    // Analogous to what 3rd party code is doing: 
    var typeConverter = TypeDescriptor.GetConverter(typeof(string)); 
    // writes "Am I convertible? false" 
    Console.WriteLine("Am I convertible? {0}", typeConverter.CanConvertTo(typeof(MyCustomType))); 
} 
+0

http://msdn.microsoft.com/en-us/library/ayybcxe5.aspx好的地方開始閱讀希望它有幫助 – MethodMan 2013-02-21 15:50:08

+0

可能你shuld註冊你的轉換器? – gabba 2013-02-21 15:51:23

+0

@gabba:謹慎地闡述?還是我應該坐在這裏用stoopid棍子毆打自己? – 2013-02-21 16:03:56

回答

4

您檢查CanConvertTo所以添加到您的轉換器:

public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) 
    { 
     return (destinationType == typeof(MyCustomType)) || base.CanConvertTo(context, destinationType); 
    } 

一些地方:

public static void Register<T, TC>() where TC : TypeConverter 
    { 
     Attribute[] attr = new Attribute[1]; 
     TypeConverterAttribute vConv = new TypeConverterAttribute(typeof(TC)); 
     attr[0] = vConv; 
     TypeDescriptor.AddAttributes(typeof(T), attr); 
    } 

和主:

Register<string, TypeConverterForMyCustomType>();    
var typeConverter = TypeDescriptor.GetConverter(typeof(string)); 

你的樣品shuld之後的工作。

+1

你是一個溫柔的男人,我爲昨天可能希望你生病的病人表示歉意......坦率地說,我確實希望快速明確起來:) – 2013-02-22 10:37:00

相關問題