Python杂文——CShap脚本生成辅助工具

  1. 简介
  2. 代码
  3. 示例
  4. 总结

原文地址

简介

本文介绍了一个用于辅助生成C#脚本的Python工具。该工具可以帮助用户快速生成C#脚本,并提供了一些常用的代码生成方法。

代码

import os

from PathUtil import ScriptsPath


class CSScriptBuilder(list):
    BlackNum = 0

    def Append(self, message):
        if self.BlackNum > 0:
            self.append('\t' * self.BlackNum + message)
        else:
            self.append(message)

    def AppendEnter(self):
        self.Append('\n')

    def AppendLine(self, message):
        if len(self) > 0:
            self.append('\n')
        if self.BlackNum > 0:
            self.append('\t' * self.BlackNum + message)
        else:
            self.append(message)

    def AppendEmptyLine(self):
        self.AppendLine('')

    def AppendUsing(self, namespace):
        self.AppendLine(f'using {namespace};')

    def BeginNamespace(self, namespace):
        self.AppendLine(f'namespace {namespace}')
        self.BeginBrace()

    def EndNamespace(self):
        self.EndBrace()

    def BeginClass(self, className, modifier="public", superclass=None):
        if superclass is not None:
            self.AppendLine(f'{modifier} class {className} : {superclass}')
        else:
            self.AppendLine(f'{modifier} class {className}')
        self.BeginBrace()

    def EndClass(self):
        self.EndBrace()

    def BeginStruct(self, structName, modifier="public"):
        self.AppendLine(f'{modifier} struct {structName}')
        self.BeginBrace()

    def EndStruct(self):
        self.EndBrace()

    def BeginEnum(self, enumName, modifier="public"):
        self.AppendLine(f'{modifier} enum {enumName}')
        self.BeginBrace()

    def EndEnum(self):
        self.EndBrace()

    def AppendEnumField(self, fieldName, fieldValue):
        self.AppendLine(f'{fieldName} = {fieldValue},')

    def BeginInterface(self, interfaceName, modifier="public"):
        self.AppendLine(f'{modifier} interface {interfaceName}')
        self.BeginBrace()

    def EndInterface(self):
        self.EndBrace()

    def AppendInterfaceMethod(self, methodName, returnType='void', parameters=''):
        self.AppendLine(f'{returnType} {methodName}({parameters});')

    def AppendField(self, propertyName, propertyType, modifier="public", init=''):
        if len(init) > 0:
            self.AppendLine(f'{modifier} {propertyType} {propertyName} = {init};')
        else:
            self.AppendLine(f'{modifier} {propertyType} {propertyName};')

    def AppendProperty(self, propertyName, propertyType, field=None, modifier="public"):
        if field is not None:
            self.AppendLine(f'{modifier} {propertyType} {propertyName} => {field};')
        else:
            self.AppendLine(f'{modifier} {propertyType} {propertyName} {{ get; set; }}')

    def BeginProperty(self, propertyName, propertyType, modifier="public"):
        self.AppendLine(f'{modifier} {propertyType} {propertyName}')
        self.BeginBrace()

    def EndProperty(self):
        self.EndBrace()

    def BeginMethod(self, methodName, modifier="public", returnType='void', parameters=''):
        self.AppendLine(f'{modifier} {returnType} {methodName}({parameters})')
        self.BeginBrace()

    def BeginConstructionMethod(self, methodName, modifier="public", parameters=''):
        self.AppendLine(f'{modifier} {methodName}({parameters})')
        self.BeginBrace()

    def EndMethod(self):
        self.EndBrace()

    def BeginIf(self, condition):
        self.AppendLine(f'if ({condition})')
        self.BeginBrace()

    def BeginElif(self, condition):
        self.AppendLine(f'else if ({condition})')
        self.BeginBrace()

    def EndIf(self):
        self.EndBrace()

    def BeginWhile(self, condition):
        self.AppendLine(f'while ({condition})')
        self.BeginBrace()

    def EndWhile(self):
        self.EndBrace()

    def BeginTry(self):
        self.AppendLine('try')
        self.BeginBrace()

    def EndTry(self):
        self.EndBrace()

    def BeginCatch(self, exceptionType):
        self.AppendLine(f'catch ({exceptionType})')
        self.BeginBrace()

    def BeginForEach(self, name, collection, singleType='var'):
        self.AppendLine(f'foreach ({singleType} {name} in {collection})')
        self.BeginBrace()

    def EndForEach(self):
        self.EndBrace()

    def BeginFor(self, condition):
        self.AppendLine(f'for ({condition})')
        self.BeginBrace()

    def EndFor(self):
        self.EndBrace()

    def BeginForRange(self, name, start, end):
        self.AppendLine(f'for (int {name} = {start}; {name} < {end}; {name}++)')
        self.BeginBrace()

    def EndForRange(self):
        self.EndBrace()

    def EndCatch(self):
        self.EndBrace()

    def BeginBlank(self):
        self.BlackNum += 1

    def EndBlank(self):
        self.BlackNum -= 1

    def BeginBrace(self):
        self.AppendLine('{')
        self.BeginBlank()

    def EndBrace(self):
        self.EndBlank()
        self.AppendLine('}')

    def BeginRegion(self, regionName):
        self.AppendLine(f'#region {regionName}')
        self.AppendEmptyLine()

    def EndRegion(self):
        self.AppendEmptyLine()
        self.AppendLine('#endregion')
        self.AppendEmptyLine()

    def ToString(self):
        return ''.join(self)

    def GenerateScript(self, fileName, isDefPath=True):
        fileName = fileName.replace('.cs', '')
        if isDefPath:
            fileName = os.path.join(ScriptsPath, fileName)
        with open(f'{fileName}.cs', 'w', encoding='utf-8') as f:
            f.write(self.ToString())

示例

def CreateTableManagerCs():
    script = CSScriptBuilder()
    script.AppendUsing('System.Collections.Generic')
    script.AppendUsing('UnityEngine')
    script.BeginNamespace(TableLoadAssembly)
    script.BeginInterface('ITable', 'public')
    script.AppendInterfaceMethod('Dispose')
    script.EndInterface()
    script.AppendEmptyLine()
    script.BeginClass('TableManager', 'public static')
    script.AppendField('s_Inited', 'bool', 'private static')
    script.AppendField('s_Cached', 'List<ITable>', 'private static', 'new List<ITable>()')
    # 添加方法
    script.AppendEmptyLine()
    script.BeginMethod("Add", parameters="ITable table")
    script.AppendLine("Debug.Assert(s_Inited, \"add but TableManager not init \");")
    script.AppendLine("s_Cached.Add(table);")
    script.EndMethod()
    script.AppendEmptyLine()
    script.BeginMethod("Remove", parameters="ITable table")
    script.AppendLine("Debug.Assert(s_Inited, \"remove but TableManager not init\");")
    script.AppendLine("if (s_Cached.Remove(table))")
    script.BeginBrace()
    script.AppendLine("table.Dispose();")
    script.EndBrace()
    script.EndMethod()
    script.AppendEmptyLine()
    script.BeginMethod("Init")
    script.AppendLine("Debug.Assert(!s_Inited, \"TableManager already init\");")
    script.AppendLine("s_Inited = true;")
    script.EndMethod()
    script.AppendEmptyLine()
    script.BeginMethod("UnInit")
    script.AppendLine("Debug.Assert(s_Inited, \"TableManager not init\");")
    script.AppendLine("s_Inited = false;")
    script.AppendLine("foreach (var table in s_Cached)")
    script.BeginBrace()
    script.AppendLine("table.Dispose();")
    script.EndBrace()
    script.AppendLine("s_Cached.Clear();")
    script.EndMethod()
    script.EndClass()
    script.EndNamespace()
    script.GenerateScript(os.path.join(ScriptsPath, 'TableManager'))

总结

以上是本文介绍的C#脚本生成辅助工具的代码示例。工具的核心是一个名为CSScriptBuilder的类,它继承自list,并提供了一系列用于生成C#脚本的方法。

通过使用这个工具,用户可以更加方便地生成C#脚本,提高开发效率。

希望本文对您理解这个工具的用途和使用方法有所帮助。如果您有任何问题或建议,欢迎留言讨论。


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 841774407@qq.com

×

喜欢就点赞,疼爱就打赏