0

I can get all type converters set explicitly in my code using attribute, but how do I get implicit type converters when using TypeDescriptor.GetConverter.

    private static string? GetTypeConverter(Compilation compilation, IPropertySymbol propertySymbol)
    {
        var typeConverterAttribute = compilation.GetTypeByMetadataName("System.ComponentModel.TypeConverterAttribute");
        if (typeConverterAttribute is null)
        {
            return null;
        }

        var propertySymbolTypeConverter = GetTypeConverter(propertySymbol, typeConverterAttribute);
        if (propertySymbolTypeConverter is not null)
        {
            return propertySymbolTypeConverter;
        }
        
        var propertySymbolTypeTypeConverter = GetTypeConverter(propertySymbol.Type, typeConverterAttribute);
        if (propertySymbolTypeTypeConverter is not null)
        {
            return propertySymbolTypeTypeConverter;
        }

        // TODO: This does not work as it uses reflection.
        // var type = Type.GetType(propertySymbol.Type.ToDisplayString());
        // if (type is not null)
        // {
        //     return TypeDescriptor.GetConverter(type).ToString();
        // }
        
        return null;
    }
4

2 回答 2

0

我发现我需要提供完全限定的类型字符串

        var format = new SymbolDisplayFormat(
            typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
            genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints | SymbolDisplayGenericsOptions.IncludeVariance
        );
        var type = Type.GetType(propertySymbol.Type.ToDisplayString(format));
        if (type is not null)
        {
            return TypeDescriptor.GetConverter(type).ToString();
        }
于 2021-01-03T12:51:51.580 回答
0

只需做框架所做的事情:

return new TypeConverter();

于 2021-01-03T12:31:54.967 回答