0

这是我的自定义类型转换器。

public class StringListTypeConverter : TypeConverter<String, IEnumerable<String>>
{
    protected override IEnumerable<string> ConvertCore(String source)
    {
        if (source == null)
            yield break;

        foreach (var item in source.Split(','))
            yield return item.Trim();
    }
}

public class Source
{
    public String Some {get;set;}
}


public class Dest
{
    public IEnumerable<String> Some {get;set;}
}

// ... configuration
Mapper.CreateMap<String, IEnumerable<String>>().ConvertUsing<StringListTypeConverter>();
Mapper.CreateMap<Source, Dest>();

问题: StringListTypeConverter 根本没有被调用。 Dest.Some == null.

更新: Automapper 版本 1.0.0.155

4

2 回答 2

1

我不知道这是否有帮助,但我只是写了一个类似的转换器,见下文。我不介意承认您的转换器中的 yield 语句让我有些困惑。:)

public class CsvToStringArrayConverter: ITypeConverter<string, string[]>
{
    #region Implementation of ITypeConverter<string,string[]>

    public string[] Convert(ResolutionContext context)
    {
        if (context.SourceValue != null && !(context.SourceValue is string))
        {
            throw new AutoMapperMappingException(context, string.Format("Value supplied is of type {0} but expected {1}.\nChange the type converter source type, or redirect the source value supplied to the value resolver using FromMember.", 
                                                                        typeof(string), context.SourceValue.GetType()));
        }

        var list = new List<string>();
        var value = (string) context.SourceValue;

        if(!string.IsNullOrEmpty(value))
            list.AddRange(value.Split(','));

        return list.ToArray();
    }

    #endregion
}

希望对您有所帮助,如果我完全误解了您的问题,请道歉!

于 2010-04-02T23:46:39.100 回答
1

经验证, Automapper 1.1 RTW一切正常

于 2010-07-12T07:25:57.963 回答