Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 带接口的类型转换器_C#_.net_Typeconverter - Fatal编程技术网

C# 带接口的类型转换器

C# 带接口的类型转换器,c#,.net,typeconverter,C#,.net,Typeconverter,我在将C#中的属性作为设计器类型实现时遇到了一些问题。 基本上,我有多个实现接口的具体类型。我想在设计时选择哪种混凝土类型 我曾尝试在ConvertFrom和ConvertTo中实现IsSummalizable,但没有效果,并尝试使用第二个Visual Studio实例对其进行调试,但我甚至无法捕获此错误。有什么想法吗?在ConvertFrom实现中,如果收到有意义的字符串(例如“MaxSummary”),则需要返回实际类型的实例,而不是调用基本方法(如Carsten所说) 您可以尝试使用反射

我在将C#中的属性作为设计器类型实现时遇到了一些问题。 基本上,我有多个实现接口的具体类型。我想在设计时选择哪种混凝土类型



我曾尝试在ConvertFrom和ConvertTo中实现IsSummalizable,但没有效果,并尝试使用第二个Visual Studio实例对其进行调试,但我甚至无法捕获此错误。有什么想法吗?

ConvertFrom
实现中,如果收到有意义的字符串(例如“MaxSummary”),则需要返回实际类型的实例,而不是调用基本方法(如Carsten所说)

您可以尝试使用反射(查找具有该名称的类型,检查它是否是
issummarizable
,调用构造函数),或者使用switch语句

使用反射,您的代码将是:

public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
    if (value is string)
    {
        var source = (string)value;
        var sourceType = Type.GetType(source);

        if (sourceType != null && typeof(ISummarizable).IsAssignableFrom(sourceType))
        {
            var constructor = sourceType.GetConstructor(Type.EmptyTypes);
            var sourceInstance = constructor.Invoke(new object[0]);

            return sourceInstance;
        }
    }

    return base.ConvertFrom(context, culture, value);
}

你期待什么?您正在告诉系统,您可以通过转到基本情况(根本不知道如何执行此操作)将
字符串
转换为
isummarizable
!只需添加一个简单的改进的“ConvertTo”(请参见编辑原文),它的效果非常好!
Object of type System.String cannot be converted to type Example.ISummarizable
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
    if (value is string)
    {
        var source = (string)value;
        var sourceType = Type.GetType(source);

        if (sourceType != null && typeof(ISummarizable).IsAssignableFrom(sourceType))
        {
            var constructor = sourceType.GetConstructor(Type.EmptyTypes);
            var sourceInstance = constructor.Invoke(new object[0]);

            return sourceInstance;
        }
    }

    return base.ConvertFrom(context, culture, value);
}