【发布时间】:2013-01-27 05:38:40
【问题描述】:
我想为泛型类创建一个TypeConverter,如下所示:
[TypeConverter(typeof(WrapperConverter<T>))]
public class Wrapper<T>
{
public T Value
{
// get & set
}
// other methods
}
public class WrapperConverter<T> : TypeConverter<T>
{
// only support To and From strings
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
T inner = converter.ConvertTo(value, destinationType);
return new Wrapper<T>(inner);
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(System.String))
{
Wrapper<T> wrapper = value as Wrapper<T>();
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
return converter.ConvertTo(wrapper.Value, destinationType);
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
问题在于你不能在这一行中使用泛型,这是不允许的:
[TypeConverter(typeof(WrapperConverter<T>))]
public class Wrapper<T>
我的下一个方法是尝试定义一个可以处理任何Wrapper<T> 实例的单个非泛型转换器。反射和泛型的混合让我难以理解如何实现两种ConvertTo 和ConvertFrom 方法。
例如,我的 ConvertTo 如下所示:
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(System.String)
&& value.GetType().IsGenericType)
{
// 1. How do I enforce that value is a Wrapper<T> instance?
Type innerType = value.GetType().GetGenericArguments()[0];
TypeConverter converter = TypeDescriptor.GetConverter(innerType);
// 2. How do I get to the T Value property? Introduce an interface that Wrapper<T> implements maybe?
object innerValue = ???
return converter.ConvertTo(innerValue, destinationType);
}
return base.ConvertTo(context, culture, value, destinationType);
}
在ConvertFrom 中我遇到了最大的问题,因为我无法知道将传入的字符串转换为哪个 Wrapper 类。
我创建了几个自定义类型和 TypeConverters 用于 ASP.NET 4 Web API 框架,这也是我需要使用它的地方。
我尝试的另一件事是在运行时分配通用版本的转换器,如 here 所示,但 WebAPI 框架不尊重它(意味着从未创建转换器)。
最后一点,我使用的是 .NET 4.0 和 VS 2010。
【问题讨论】:
-
我之前已经解决了这个问题,我相信我使用 dynamic 来转换 T 并使用 typeof 。我明天应该可以发布我的解决方案,因为我目前无法访问代码。
-
@awright18 谢谢,但我没有我需要的东西。我的问题主要是如何为泛型类型创建和关联 TypeConverter。
标签: c# visual-studio-2010 asp.net-web-api asp.net-4.0 typeconverter