将包含属性的上下文传递给TypeConverter

时间:2015-02-27 13:10:14

标签: c# type-conversion typeconverter typedescriptor icustomtypedescriptor

我正在寻找一种将附加信息传递给TypeConverter的方法,以便为转换提供一些上下文,而无需创建自定义构造函数。

传递的额外信息将是原始对象(在编译时称为接口),其中包含我正在转换的属性。它包含自己的属性,如Id,可用于查找转换相关信息。

我已经查看了ITypeDescriptorContext的文档,但我还没有找到如何实现该界面的明确示例。我也不相信它是我需要的工具。

目前,在我的代码中我打电话:

// For each writeable property in my output class.

// If property has TypeConverterAttribute
var converted = converter.ConvertFrom(propertyFromOriginalObject)

propertyInfo.SetValue(output, converted, null);

我想做的就像是。

// Original object is an interface at compile time.
var mayNewValue = converter.ConvertFrom(originalObject, propertyFromOriginalObject)

我希望能够使用其中一个重载来执行我需要的操作,以便任何自定义转换器都可以继承自TypeConverter而不是具有自定义构造函数的基类,因为这会使生命变得更好使用依赖注入更容易,并使用MVC中的DependencyResolver.Current.GetService(type)来初始化我的转换器。

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

您要使用的方法显然是这种重载:TypeConverter.ConvertFrom Method (ITypeDescriptorContext, CultureInfo, Object)

它将允许您传递非常通用的上下文。 Instance属性表示您正在处理的对象实例,PropertyDescriptor属性表示要转换的属性值的属性定义。

例如,Winforms属性网格就是这样做的。

因此,您必须提供自己的背景信息。这是一个样本:

public class MyContext : ITypeDescriptorContext
{
    public MyContext(object instance, string propertyName)
    {
        Instance = instance;
        PropertyDescriptor = TypeDescriptor.GetProperties(instance)[propertyName];
    }

    public object Instance { get; private set; }
    public PropertyDescriptor PropertyDescriptor { get; private set; }
    public IContainer Container { get; private set; }

    public void OnComponentChanged()
    {
    }

    public bool OnComponentChanging()
    {
        return true;
    }

    public object GetService(Type serviceType)
    {
        return null;
    }
}

所以,让我们考虑一个自定义转换器,因为你可以看到它可以使用一行代码获取现有对象的属性值(请注意,此代码与标准的现有ITypeDescriptorContext兼容,如属性网格一虽然在现实生活场景中,您必须检查上下文的无效性):

public class MyTypeConverter : TypeConverter
{
    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        // get existing value
        object existingPropertyValue = context.PropertyDescriptor.GetValue(context.Instance);

        // do something useful here
        ...
    }
}

现在,如果您要修改此自定义对象:

public class MySampleObject
{
    public MySampleObject()
    {
        MySampleProp = "hello world";
    }

    public string MySampleProp { get; set; }
}

您可以像这样调用转换器:

MyTypeConverter tc = new MyTypeConverter();
object newValue = tc.ConvertFrom(new MyContext(new MySampleObject(), "MySampleProp"), null, "whatever");