如何导入 C# 字典中定义的类型?

imports当对象上的属性是字典并且其值是自定义类型时,我正在努力弄清楚如何生成我的行。


我的 DTO/C# 类定义如下。我的 .tst 文件中的 Imports 函数没有发现它需要导入Status类型,类似于它的导入方式ProjectDTO。


有没有办法在 .tst 文件中获取字典值的类型?


C# 文件


[TypeScript]

public class ActiveProjectsViewModel

{

    public List<ProjectDTO> Projects { get; set; }


    public Dictionary<int,Status> Statuses { get; set; }


    public bool EditModeAvailable { get; set; }

}

.tst 文件


 ${

string Imports(Class c)

        {

            var props = c.Properties.Where(p=>!p.Attributes.Any(a => String.Equals(a.name, "TypeScriptIgnore", StringComparison.OrdinalIgnoreCase)));


            IEnumerable<Type> types = props

                .Select(p => p.Type)

                .Where(t => !t.IsPrimitive || t.IsEnum)

                .Select(t => t.IsGeneric ? t.TypeArguments.First() : t)

                .Where(t => !t.Attributes.Any(a => String.Equals(a.name, "TypeScriptIgnore", StringComparison.OrdinalIgnoreCase)))

                .Distinct();


            return string.Join(Environment.NewLine, types.Select(t => $"import {{ {t.Name} }} from './{t.Name}';").Distinct());

        }

    }


    $Classes()[

    $Imports


    export class $Name {

        $Properties($PropertyIsNotIgnored)[        

        public $name: $Type = $Type[$Default];]

        $BaseClass[$Properties($PropertyIsNotIgnored)[

        public $name: $Type = $Type[$Default];]]

    }]



    $Enums(*)[

    export enum $Name {

        $Values[

        $Name = $Value][,]

    }]

生成此文件:


import { ProjectDTO } from './ProjectDTO';


export class ActiveProjectsViewModel {


    public projects: ProjectDTO[] = [];        


    public statuses: { [key: number]: Status; } = {};        


    public editModeAvailable: boolean = false;


}


侃侃尔雅
浏览 208回答 1
1回答

PIPIONE

从这里发布的打字机的创建者:https ://github.com/frhagn/Typewriter/issues/282 看起来字典中定义的类型可以使用以下方法派生。该SelectMany行是添加的关键之一。string Imports(Class c){&nbsp; &nbsp; var props = c.Properties.Where(p => !p.Attributes.Any(a => String.Equals(a.name, "TypeScriptIgnore", StringComparison.OrdinalIgnoreCase)));&nbsp; &nbsp; IEnumerable<Type> types = props&nbsp; &nbsp; &nbsp; &nbsp; .Select(p => p.Type)&nbsp; &nbsp; &nbsp; &nbsp; .SelectMany(t => t.IsGeneric ? t.TypeArguments : new[] { t } as IEnumerable<Type>)&nbsp; &nbsp; &nbsp; &nbsp; .Where(t => !t.IsPrimitive || t.IsEnum)&nbsp; &nbsp; &nbsp; &nbsp; .Where(t => !t.Attributes.Any(a => String.Equals(a.name, "TypeScriptIgnore", StringComparison.OrdinalIgnoreCase)))&nbsp; &nbsp; &nbsp; &nbsp; .Distinct();&nbsp; &nbsp; return string.Join(Environment.NewLine, types.Select(t => $"import {{ {t.Name} }} from './{t.Name}';").Distinct());}
打开App,查看更多内容
随时随地看视频慕课网APP