2013-02-21 68 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

相关问题