【问题标题】:Modelina Csharp Generator Add InheritanceModelina Csharp 生成器添加继承
【发布时间】:2022-06-16 19:23:08
【问题描述】:

我在玩asyncapi/modelina CSharpGenerator。我想将继承添加到生成的类中,如下所示

 public class UserCreated: IEvent
    {
      
    }

那可能吗?除了生成的依赖项之外,我们可以添加其他依赖项吗?

【问题讨论】:

    标签: asyncapi


    【解决方案1】:

    不幸的是,继承是one of those features that have gotten put on the backburner, and still is.

    幸运的是,它是可以实现的,但它确实需要您覆盖整个渲染行为,从长远来看这可能无法维护。您可以在此 PR 中找到完整示例:https://github.com/asyncapi/modelina/pull/772

    const generator = new CSharpGenerator({
      presets: [
        {
          class: {
            // Self is used to overwrite the entire rendering behavior of the class
            self: async ({renderer, options, model}) => {
              //Render all the class content
              const content = [
                await renderer.renderProperties(),
                await renderer.runCtorPreset(),
                await renderer.renderAccessors(),
                await renderer.runAdditionalContentPreset(),
              ];
    
              if (options?.collectionType === 'List' ||
                model.additionalProperties !== undefined ||
                model.patternProperties !== undefined) {
                renderer.addDependency('using System.Collections.Generic;');
              }
    
              const formattedName = renderer.nameType(model.$id);
              return `public class ${formattedName} : IEvent
    {
    ${renderer.indent(renderer.renderBlock(content, 2))}
    }`;
            }
          }
        }
      ]
    });
    

    这里发生的事情是,我们为类渲染器创建了一个自定义预设,并覆盖了 itself 的整个渲染过程。

    这将生成based on this input

    public class Root : IEvent
    {
      private string[] email;
      public string[] Email 
      {
        get { return email; }
        set { email = value; }
      }
    }
    

    关于依赖关系,请参阅https://github.com/asyncapi/modelina/blob/master/docs/presets.md#adding-new-dependencies。您可以在 self 预设挂钩中执行此操作。

    您可以在此处阅读有关预设的更多信息:https://github.com/asyncapi/modelina/blob/master/docs/presets.md

    【讨论】:

      猜你喜欢
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      • 2013-07-07
      • 2015-09-12
      • 2012-09-07
      • 2021-12-29
      • 1970-01-01
      相关资源
      最近更新 更多