Typelite: Why is Dictionary mapped to KeyValuePair and not to any or [index:string]:any

前端 未结 3 1233
遥遥无期
遥遥无期 2021-02-14 21:16

I have a class,

public class Instance : IResource
{
   public Dictionary Value { get; set; }

and it is mapped to

<
3条回答
  •  难免孤独
    2021-02-14 21:46

    Collection types (any type implementing IEnumerable) is converted to arrays. Dictionary<> implements IEnumerable> and thus is converted to an array. The item-type is then expanded to its fully qualified name (FQN): System.Collections.Generic.KeyValuePair.

    Using Type Converters will let you change the type-name, but not the FQN. So it is only applicable to local types. In the case of dictionaries, you can't change the item type by inheritance.

    You could either create a new dictionary type, without inheriting from Dictionary<>. Another way around this problem, is to also use Type Formatters:

    ts.WithConvertor>(t => {
        // Embed the real type in $
        // "System.Collections.Generic.${ [key: string]: any }$[]"
        return "${ [key: string]: any }$";
    });
    ts.WithFormatter((string memberTypeName, bool isMemberCollection) => {
        // Extract the content inside $
        string[] pieces = memberTypeName.Split('$');
        if (pieces.Length == 3) return pieces[1];
        // Default behaviour
        return memberTypeName + (isMemberCollection ? "[]" : "");
    });
    

提交回复
热议问题