且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在当前文档中的 Visual Studio 中生成代码?

更新时间:2023-01-28 12:37:22

你可以试试我的 Visual Commander 专为这种轻量级可扩展性而设计的扩展.它允许将文档编辑为文本或使用 Visual Studio 代码模型和 Roslyn.

You can try my Visual Commander extension which is designed exactly for such kind of lightweight extensibility. It allows to edit a document as text or use Visual Studio code model and Roslyn.

例如,当插入符号位于变量声明中的 _rigidbody 或 _myComponent 时,调用以下命令:

For example, call the following command when the caret is on _rigidbody or _myComponent in a variable declaration:

public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
    {
        this.DTE = DTE;

        EnvDTE.CodeVariable v = FindCurrentVariable();
        if (v != null)
        {
            string initialization = v.Name + " = GetComponent<" + v.Type.CodeType.Name + ">();";
            AddLine(FindFunction("Start"), initialization);
        }
    }

    EnvDTE.CodeFunction FindFunction(string name)
    {
        EnvDTE.TextSelection ts = DTE.ActiveWindow.Selection as EnvDTE.TextSelection;
        if (ts == null)
            return null;
        EnvDTE.CodeClass codeClass = ts.ActivePoint.CodeElement[EnvDTE.vsCMElement.vsCMElementClass]
            as EnvDTE.CodeClass;
        if (codeClass == null)
            return null;
        foreach (EnvDTE.CodeElement elem in codeClass.Members)
        {
            if (elem.Kind == EnvDTE.vsCMElement.vsCMElementFunction && elem.Name == name)
                return elem as EnvDTE.CodeFunction;
        }
        return null;
    }

    EnvDTE.CodeVariable FindCurrentVariable()
    {
        EnvDTE.TextSelection ts = DTE.ActiveWindow.Selection as EnvDTE.TextSelection;
        if (ts == null)
            return null;
        return ts.ActivePoint.CodeElement[EnvDTE.vsCMElement.vsCMElementVariable]
            as EnvDTE.CodeVariable;
    }

    void AddLine(EnvDTE.CodeFunction f, string text)
    {
        EnvDTE.TextPoint tp = f.GetStartPoint(EnvDTE.vsCMPart.vsCMPartBody);
        EnvDTE.EditPoint p = tp.CreateEditPoint();
        p.Insert(text + System.Environment.NewLine);
        p.SmartFormat(tp);
    }

    EnvDTE80.DTE2 DTE;
}