我正在使用一些第三方代碼,它使用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)));
}
http://msdn.microsoft.com/en-us/library/ayybcxe5.aspx好的地方開始閱讀希望它有幫助 – MethodMan 2013-02-21 15:50:08
可能你shuld註冊你的轉換器? – gabba 2013-02-21 15:51:23
@gabba:謹慎地闡述?還是我應該坐在這裏用stoopid棍子毆打自己? – 2013-02-21 16:03:56