• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# CodeDom.CodeSnippetStatement类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.CodeDom.CodeSnippetStatement的典型用法代码示例。如果您正苦于以下问题:C# CodeSnippetStatement类的具体用法?C# CodeSnippetStatement怎么用?C# CodeSnippetStatement使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



CodeSnippetStatement类属于System.CodeDom命名空间,在下文中一共展示了CodeSnippetStatement类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Constructor1

		public void Constructor1 ()
		{
			string stmt = "mono";

			CodeSnippetStatement css = new CodeSnippetStatement (stmt);
			Assert.IsNull (css.LinePragma, "#1");

			Assert.IsNotNull (css.Value, "#2");
			Assert.AreEqual (stmt, css.Value, "#3");
			Assert.AreSame (stmt, css.Value, "#4");

			Assert.IsNotNull (css.StartDirectives, "#5");
			Assert.AreEqual (0, css.StartDirectives.Count, "#6");

			Assert.IsNotNull (css.EndDirectives, "#7");
			Assert.AreEqual (0, css.EndDirectives.Count, "#8");

			Assert.IsNotNull (css.UserData, "#9");
			Assert.AreEqual (typeof(ListDictionary), css.UserData.GetType (), "#10");
			Assert.AreEqual (0, css.UserData.Count, "#11");
			
			css.Value = null;
			Assert.IsNotNull (css.Value, "#12");
			Assert.AreEqual (string.Empty, css.Value, "#13");

			CodeLinePragma clp = new CodeLinePragma ("mono", 10);
			css.LinePragma = clp;
			Assert.IsNotNull (css.LinePragma, "#14");
			Assert.AreSame (clp, css.LinePragma, "#15");

			css = new CodeSnippetStatement ((string) null);
			Assert.IsNotNull (css.Value, "#16");
			Assert.AreEqual (string.Empty, css.Value, "#17");
		}
开发者ID:Profit0004,项目名称:mono,代码行数:34,代码来源:CodeSnippetStatementTest.cs


示例2: TypescriptSnippetStatement

 public TypescriptSnippetStatement(
     IExpressionFactory expressionFactory,
     CodeSnippetStatement statement,
     CodeGeneratorOptions options)
 {
     _expressionFactory = expressionFactory;
     _statement = statement;
     _options = options;
 }
开发者ID:s2quake,项目名称:TypescriptCodeDom,代码行数:9,代码来源:TypescriptSnippetStatement.cs


示例3: execute_Click

        private void execute_Click(object sender, EventArgs e)
        {
            // eine CompileUnit erstellen die das Programm hält
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            // namespace definieren
            CodeNamespace samples = new CodeNamespace("InjectionExample");
            // genutzte namespaces importieren
            foreach(String import in includes.CheckedItems)
                samples.Imports.Add(new CodeNamespaceImport(import));

            samples.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            // namespaces zur CompileUnit hinzufügen
            compileUnit.Namespaces.Add(samples);

            // eine neue Klasse definieren
            CodeTypeDeclaration container = new CodeTypeDeclaration("CodeContainerClass");
            // Klasse hinzufügen
            samples.Types.Add(container);

            /*
             * eine public methode erstellen
             */
            CodeMemberMethod pub_method = new CodeMemberMethod();
            pub_method.Name = "execute";
            pub_method.ReturnType = new CodeTypeReference("System.Double");
            pub_method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            pub_method.Parameters.Add(new CodeParameterDeclarationExpression("Label", "label"));
            CodeSnippetStatement input = new CodeSnippetStatement();
            input.Value = code.Text;
            pub_method.Statements.Add(input);
            container.Members.Add(pub_method); // der Klasse die Methode hinzufügen

            CodeDOMTest.Generator gen;
            if(radio_csharp.Checked)
                gen = new CodeDOMTest.Generator(new CSharpCodeProvider());
            else
                gen = new CodeDOMTest.Generator(new VBCodeProvider());

            // Quellfile erstellen
            String gen_code = gen.GenerateCSharpCode(compileUnit);
            gencode.ResetText();
            gencode.Text = gen_code;

            // Quellfile compilieren
            String compiler_message;
            Assembly compiled_code = gen.CompileCSharpCode(gen_code, out compiler_message);
            compiler_output.ResetText();
            compiler_output.Text = compiler_message;

            // execute the Assembly
            if (compiled_code != null)
            {
                Object[] args = {change_label};
                Double ret = (Double)gen.InvokeMethod(compiled_code, "CodeContainerClass", "execute", args);
                result.Text = ret.ToString();
            }
        }
开发者ID:mYstar,项目名称:CSharpCodeInjection,代码行数:57,代码来源:Form1.cs


示例4: GenerateRenderMemberMethod

        // Generate the CodeDom for our render method
        internal CodeMemberMethod GenerateRenderMemberMethod(string virtualPath)
        {
            Control container = Parent;

            string physicalPath = HostingEnvironment.MapPath(virtualPath);

            CodeMemberMethod renderMethod = new CodeMemberMethod();
            renderMethod.Name = RenderMethodName;
            renderMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "__srh"));

            // REVIEW: we need support for CodeArgumentReferenceExpression, as using a snippet is
            // not guanranteed to be language agnostic
            CodeExpression snippetRenderHelper = new CodeArgumentReferenceExpression("__srh");

            // Go through all the children to build the CodeDOM tree
            for (int controlIndex = 0; controlIndex < container.Controls.Count; controlIndex++) {
                Control c = container.Controls[controlIndex];

                if (!(c is SnippetControl || c is ExpressionSnippetControl)) {

                    // If it's a regular control, generate a call to render it based on its index

                    CodeExpression method = new CodeMethodInvokeExpression(snippetRenderHelper, "RenderControl",
                        new CodePrimitiveExpression(controlIndex));
                    renderMethod.Statements.Add(new CodeExpressionStatement(method));

                    continue;
                }

                BaseCodeControl codeControl = (BaseCodeControl)c;

                string code = codeControl.Code;
                CodeStatement stmt;

                if (codeControl is SnippetControl) {

                    // If it's a <% code %> block, just append the code as is

                    stmt = new CodeSnippetStatement(code);
                } else {

                    // If it's a <%= expr %> block, generate a call to render it

                    CodeExpression method = new CodeMethodInvokeExpression(snippetRenderHelper, "Render",
                        new CodeSnippetExpression(code));
                    stmt = new CodeExpressionStatement(method);
                }

                stmt.LinePragma = new CodeLinePragma(physicalPath, codeControl.Line);
                renderMethod.Statements.Add(stmt);
            }

            return renderMethod;
        }
开发者ID:TerabyteX,项目名称:main,代码行数:55,代码来源:SnippetControl.cs


示例5: AddDesignTimeHelperStatement

 public void AddDesignTimeHelperStatement(CodeSnippetStatement statement)
 {
     if (_designTimeHelperMethod == null)
     {
         _designTimeHelperMethod = new CodeMemberMethod()
         {
             Name = DesignTimeHelperMethodName,
             Attributes = MemberAttributes.Private
         };
         _designTimeHelperMethod.Statements.Add(
             new CodeSnippetStatement(BuildCodeString(cw => cw.WriteDisableUnusedFieldWarningPragma())));
         _designTimeHelperMethod.Statements.Add(
             new CodeSnippetStatement(BuildCodeString(cw => cw.WriteRestoreUnusedFieldWarningPragma())));
         GeneratedClass.Members.Insert(0, _designTimeHelperMethod);
     }
     _designTimeHelperMethod.Statements.Insert(_designTimeHelperMethod.Statements.Count - 1, statement);
 }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:17,代码来源:CodeGeneratorContext.cs


示例6: DecideFrame

		/* sample super simple framedecider
		using CNCMaps.Engine.Map;

		namespace SampleSimpleFramedecider {
			class FrameDecider {
				public static int DecideFrame(GameObject obj) {
					if (obj is OwnableObject)
						return (obj as OwnableObject).Direction / 32;
					else
						return 0;
				}
			}
		}
		*/

		public static Func<GameObject, int> CompileFrameDecider(string codeStr) {
			var unit = new CodeCompileUnit();
			var ns = new CodeNamespace("DynamicFrameDeciders");
			ns.Imports.Add(new CodeNamespaceImport("CNCMaps.Engine.Map"));
			unit.Namespaces.Add(ns);

			var @class = new CodeTypeDeclaration("FrameDecider"); //Create class
			ns.Types.Add(@class);

			var method = new CodeMemberMethod();
			method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
			//Make this method an override of base class's method
			method.Name = "DecideFrame";
			method.ReturnType = new CodeTypeReference(typeof(int));
			method.Parameters.Add(new CodeParameterDeclarationExpression("GameObject", "obj"));
			var code = new CodeSnippetStatement(codeStr + ";");
			method.Statements.Add(new CodeSnippetStatement("int frame = 0;"));
			method.Statements.Add(code);
			method.Statements.Add(new CodeSnippetStatement("return frame;"));
			@class.Members.Add(method); //Add method to the class

			// compile DOM
			CodeDomProvider cp = CodeDomProvider.CreateProvider("CS");
			var options = new CompilerParameters();
			
			options.GenerateInMemory = true;
			options.ReferencedAssemblies.Add(typeof(Map.Map).Assembly.Location);
			options.ReferencedAssemblies.Add(typeof(CNCMaps.Shared.ModConfig).Assembly.Location);
			var cpRes = cp.CompileAssemblyFromDom(options, unit);
			AppDomain localDom = AppDomain.CreateDomain("x");

			// now bind the method
			MethodInfo mi = cpRes.CompiledAssembly.GetType("DynamicFrameDeciders.FrameDecider").GetMethod("DecideFrame");

			// and wrap it
			return obj => (int)mi.Invoke(null, new[] {obj});
		}
开发者ID:dkeetonx,项目名称:ccmaps-net,代码行数:52,代码来源:FrameDeciderCompiler.cs


示例7: WriteSnippetStatement

        protected override void WriteSnippetStatement(CodeSnippetStatement s) {
            string snippet = s.Value;

            // Finally, append the snippet. Make sure that it is indented properly if
            // it has nested newlines
            Writer.Write(IndentSnippetStatement(snippet));
            Writer.Write('\n');

            // See if the snippet changes our indent level
            string lastLine = snippet.Substring(snippet.LastIndexOf('\n') + 1);
            // If the last line is only whitespace, then we have a new indent level
            if (lastLine.Trim('\t', ' ') == "") {
                lastLine = lastLine.Replace("\t", "        ");
                int indentLen = lastLine.Length;
                if (indentLen > _indents.Peek()) {
                    _indents.Push(indentLen);
                }
                else {
                    while (indentLen < _indents.Peek()) {
                        _indents.Pop();
                    }
                }
            }
        }
开发者ID:jcteague,项目名称:ironruby,代码行数:24,代码来源:PythonCodeDomCodeGen.cs


示例8: GenerateCode

        public override void GenerateCode(Span target, CodeGeneratorContext context)
        {
            context.GeneratedClass.BaseTypes.Clear();
            context.GeneratedClass.BaseTypes.Add(new CodeTypeReference(ResolveType(context, BaseType.Trim())));

            if (context.Host.DesignTimeMode)
            {
                int generatedCodeStart = 0;
                string code = context.BuildCodeString(cw =>
                {
                    generatedCodeStart = cw.WriteVariableDeclaration(target.Content, "__inheritsHelper", null);
                    cw.WriteEndStatement();
                });

                int paddingCharCount;

                CodeSnippetStatement stmt = new CodeSnippetStatement(
                    CodeGeneratorPaddingHelper.Pad(context.Host, code, target, generatedCodeStart, out paddingCharCount))
                {
                    LinePragma = context.GenerateLinePragma(target, generatedCodeStart + paddingCharCount)
                };
                context.AddDesignTimeHelperStatement(stmt);
            }
        }
开发者ID:huangw-t,项目名称:aspnetwebstack,代码行数:24,代码来源:SetBaseTypeCodeGenerator.cs


示例9: CodeLanguageSnippetStatement

 public CodeLanguageSnippetStatement(CodeSnippetStatement csStatement, CodeSnippetStatement vbStatement)
 {
     _csStatement = csStatement;
     _vbStatement = vbStatement;
 }
开发者ID:laymain,项目名称:CodeDomUtils,代码行数:5,代码来源:CodeSnippetStatement.cs


示例10: EnsureStyleConnector

        private CodeMemberMethod EnsureStyleConnector()
        {
            if (_ccRoot.StyleConnectorFn == null)
            {
                _ccRoot.StyleConnectorFn = new CodeMemberMethod();
                _ccRoot.StyleConnectorFn.Name = CONNECT;
                _ccRoot.StyleConnectorFn.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                _ccRoot.StyleConnectorFn.PrivateImplementationType = new CodeTypeReference(KnownTypes.Types[(int)KnownElements.IStyleConnector]);

                // void IStyleConnector.Connect(int connectionId, object target) {
                //
                CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(int), CONNECTIONID);
                CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression(typeof(object), TARGET);
                _ccRoot.StyleConnectorFn.Parameters.Add(param1);
                _ccRoot.StyleConnectorFn.Parameters.Add(param2);

                AddDebuggerNonUserCodeAttribute(_ccRoot.StyleConnectorFn);
                AddGeneratedCodeAttribute(_ccRoot.StyleConnectorFn);
                AddEditorBrowsableAttribute(_ccRoot.StyleConnectorFn);
                AddSuppressMessageAttribute(_ccRoot.StyleConnectorFn, "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes");
                AddSuppressMessageAttribute(_ccRoot.StyleConnectorFn, "Microsoft.Performance", "CA1800:DoNotCastUnnecessarily");
                AddSuppressMessageAttribute(_ccRoot.StyleConnectorFn, "Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity");

                if (SwitchStatementSupported())
                {
                    // switch (connectionId) -- Start Switch
                    // {
                    CodeSnippetStatement css = new CodeSnippetStatement(SWITCH_STATEMENT);
                    _ccRoot.StyleConnectorFn.Statements.Add(css);
                }
            }

            return _ccRoot.StyleConnectorFn;
        }
开发者ID:krytht,项目名称:DotNetReferenceSource,代码行数:34,代码来源:MarkupCompiler.cs


示例11: ConnectNameAndEvents

        internal void ConnectNameAndEvents(string elementName, ArrayList events, int connectionId)
        {
            CodeContext cc = (CodeContext)_codeContexts.Peek();
            bool isAllowedNameScope = cc.IsAllowedNameScope;

            if (_codeContexts.Count > 1 && KnownTypes.Types[(int)KnownElements.INameScope].IsAssignableFrom(cc.ElementType))
            {
                cc.IsAllowedNameScope = false;
            }

            if ((elementName == null || !isAllowedNameScope) && (events == null || events.Count == 0))
            {
                _typeArgsList = null;
                return;
            }

            EnsureHookupFn();

            CodeConditionStatement ccsConnector = null;

            if (SwitchStatementSupported())
            {
                // case 1:
                //
                CodeSnippetStatement cssCase = new CodeSnippetStatement(CASE_STATEMENT + connectionId + COLON);
                _ccRoot.HookupFn.Statements.Add(cssCase);
            }
            else
            {
                // if (connectionId == 1)
                //
                ccsConnector = new CodeConditionStatement();
                ccsConnector.Condition = new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CONNECTIONID),
                                                                          CodeBinaryOperatorType.ValueEquality,
                                                                          new CodePrimitiveExpression(connectionId));
            }


            // (System.Windows.Controls.Footype)target;
            CodeArgumentReferenceExpression careTarget = new CodeArgumentReferenceExpression(TARGET);
            CodeCastExpression cceTarget = new CodeCastExpression(cc.ElementTypeReference, careTarget);
            CodeExpression ceEvent = cceTarget;

            // Names in nested Name scopes not be hooked up via ICC.Connect() as no fields are generated in this case.
            if (elementName != null && isAllowedNameScope)
            {
                // this.fooId = (System.Windows.Controls.Footype)target;
                //
                ceEvent = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), elementName);
                CodeAssignStatement casName = new CodeAssignStatement(ceEvent, cceTarget);
                if (SwitchStatementSupported())
                {
                    _ccRoot.HookupFn.Statements.Add(casName);
                }
                else
                {
                    ccsConnector.TrueStatements.Add(casName);
                }
            }

            if (events != null)
            {
                foreach (MarkupEventInfo mei in events)
                {
                    CodeStatement csEvent = AddCLREvent(cc, ceEvent, mei);

                    if (SwitchStatementSupported())
                    {
                        _ccRoot.HookupFn.Statements.Add(csEvent);
                    }
                    else
                    {
                        ccsConnector.TrueStatements.Add(csEvent);
                    }
                }
            }

            // return;
            //
            if (SwitchStatementSupported())
            {
                _ccRoot.HookupFn.Statements.Add(new CodeMethodReturnStatement());
            }
            else
            {
                ccsConnector.TrueStatements.Add(new CodeMethodReturnStatement());
                _ccRoot.HookupFn.Statements.Add(ccsConnector);
            }

            _typeArgsList = null;
        }
开发者ID:krytht,项目名称:DotNetReferenceSource,代码行数:91,代码来源:MarkupCompiler.cs


示例12: GenerateSnippetStatement

 protected override void GenerateSnippetStatement(CodeSnippetStatement e)
 {
     base.Output.WriteLine(e.Value);
 }
开发者ID:laymain,项目名称:CodeDomUtils,代码行数:4,代码来源:VBCodeGenerator.cs


示例13: GenerateSnippetStatement

		protected virtual void GenerateSnippetStatement (CodeSnippetStatement s)
		{
			output.WriteLine (s.Value);
		}
开发者ID:carrie901,项目名称:mono,代码行数:4,代码来源:CodeGenerator.cs


示例14: GetTableClass

        static string GetTableClass(DataTable TableSchema, string ClassNamespace, string ClassName)
        {
            string result = string.Empty;

            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            CodeNamespace tableClassNamespace = new CodeNamespace(ClassNamespace);
            codeCompileUnit.Namespaces.Add(tableClassNamespace);

            //we need this for AppDomain to work since we need to use MarshalByRefObject
            CodeNamespaceImport codeNamespaceImport = null;
            codeNamespaceImport = new CodeNamespaceImport()
            {
                Namespace = "System"
            };
            tableClassNamespace.Imports.Add(codeNamespaceImport);
            codeNamespaceImport = new CodeNamespaceImport()
            {
                Namespace = "System.Reflection"
            };
            tableClassNamespace.Imports.Add(codeNamespaceImport);

            CodeTypeDeclaration trackerTableClass = new CodeTypeDeclaration()
            {
                Name = ClassName,
                IsClass = true,
                IsEnum = false,
                IsInterface = false,
                IsPartial = false,
                IsStruct = false
            };
            //we need this for AppDomain
            //trackerTableClass.BaseTypes.Add("MarshalByRefObject");
            tableClassNamespace.Types.Add(trackerTableClass);

            CodeMemberProperty columnProperty = null;
            CodeCommentStatement codeCommentStatement = null;
            CodeSnippetStatement codeSnippetStatement = null;
            CodeMethodReturnStatement codeMethodReturnStatement = null;

            //define constructor for POCO
            CodeConstructor codeConstructor = new CodeConstructor()
            {
                Attributes = MemberAttributes.Public
            };

            //add properties to the POCO
            foreach (DataRow row in from dataRow in TableSchema.Rows.Cast<DataRow>()
                                    orderby int.Parse(dataRow[ColumnOrdinal].ToString())
                                    select dataRow)
            {
                if (!bool.Parse(row[IsIdentity].ToString()))
                {
                    //create the property
                    columnProperty = new CodeMemberProperty()
                    {
                        Name = CleanColumnName(row[ColumnName].ToString()),
                        Type = new CodeTypeReference(Type.GetType(row[DataType].ToString())),
                        Attributes = MemberAttributes.Public | MemberAttributes.Final,
                        HasGet = true,
                        HasSet = false
                    };

                    //comment this property
                    codeCommentStatement = new CodeCommentStatement(string.Format("[{0}] column", row[ColumnName].ToString()));
                    columnProperty.Comments.Add(codeCommentStatement);

                    //add the get statements for this property
                    string script = GetColumnScript(row[ColumnName].ToString());

                    if (string.IsNullOrWhiteSpace(script))
                    {
                        //add comment that the script file was not found
                        codeCommentStatement = new CodeCommentStatement(string.Format("script file not found for column {0}.", row[ColumnName].ToString()));
                        columnProperty.GetStatements.Add(codeCommentStatement);
                        codeMethodReturnStatement = new CodeMethodReturnStatement(new CodeSnippetExpression(@""""""));
                        columnProperty.GetStatements.Add(codeMethodReturnStatement);

                    }
                    else
                    {
                        //add the script code snippet
                        codeSnippetStatement = new CodeSnippetStatement(script);
                        columnProperty.GetStatements.Add(codeSnippetStatement);
                    }

                    //add this property to the class
                    trackerTableClass.Members.Add(columnProperty);
                }
                else
                {
                    codeCommentStatement = new CodeCommentStatement(string.Format("Property {0} for table column {1} not created because it is the identity column.", CleanColumnName(row[ColumnName].ToString()), row[ColumnName].ToString()));
                    trackerTableClass.Comments.Add(codeCommentStatement);
                }
            }

            #region render code
            CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions()
            {
                BracingStyle = "C",
                VerbatimOrder = true,
//.........这里部分代码省略.........
开发者ID:flipthetrain,项目名称:KCDC2015_CODEDOM,代码行数:101,代码来源:Program.cs


示例15: CreateRenderMethod

        /// <summary>生成Render方法</summary>
        /// <param name="blocks"></param>
        /// <param name="lineNumbers"></param>
        /// <param name="typeDec"></param>
        private static void CreateRenderMethod(List<Block> blocks, Boolean lineNumbers, CodeTypeDeclaration typeDec)
        {
            CodeMemberMethod method = new CodeMemberMethod();
            typeDec.Members.Add(method);
            method.Name = "Render";
            method.Attributes = MemberAttributes.Override | MemberAttributes.Public;
            method.ReturnType = new CodeTypeReference(typeof(String));

            // 生成代码
            CodeStatementCollection statementsMain = method.Statements;
            Boolean firstMemberFound = false;
            foreach (Block block in blocks)
            {
                if (block.Type == BlockType.Directive) continue;
                if (block.Type == BlockType.Member)
                {
                    // 遇到类成员代码块,标识取反
                    firstMemberFound = !firstMemberFound;
                    continue;
                }
                // 只要现在还在类成员代码块区域内,就不做处理
                if (firstMemberFound) continue;

                if (block.Type == BlockType.Statement)
                {
                    // 代码语句,直接拼接
                    CodeSnippetStatement statement = new CodeSnippetStatement(block.Text);
                    if (lineNumbers)
                        AddStatementWithLinePragma(block, statementsMain, statement);
                    else
                        statementsMain.Add(statement);
                }
                else if (block.Type == BlockType.Text)
                {
                    // 模版文本,直接Write
                    if (!String.IsNullOrEmpty(block.Text))
                    {
                        CodeMethodInvokeExpression exp = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Write", new CodeExpression[] { new CodePrimitiveExpression(block.Text) });
                        //statementsMain.Add(exp);
                        CodeExpressionStatement statement = new CodeExpressionStatement(exp);
                        if (lineNumbers)
                            AddStatementWithLinePragma(block, statementsMain, statement);
                        else
                            statementsMain.Add(statement);
                    }
                }
                else
                {
                    // 表达式,直接Write
                    CodeMethodInvokeExpression exp = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Write", new CodeExpression[] { new CodeArgumentReferenceExpression(block.Text.Trim()) });
                    CodeExpressionStatement statement = new CodeExpressionStatement(exp);
                    if (lineNumbers)
                        AddStatementWithLinePragma(block, statementsMain, statement);
                    else
                        statementsMain.Add(statement);
                }
            }

            statementsMain.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Output"), "ToString"), new CodeExpression[0])));
        }
开发者ID:g992com,项目名称:esb,代码行数:64,代码来源:Template.cs


示例16: GenerateSnippetStatement

 private  void GenerateSnippetStatement(CodeSnippetStatement e) {
     Output.WriteLine(e.Value);
 }
开发者ID:gbarnett,项目名称:shared-source-cli-2.0,代码行数:3,代码来源:csharpcodeprovider.cs


示例17: GenerateCompileUnit

        public static CodeCompileUnit GenerateCompileUnit(ITextTemplatingEngineHost host, ParsedTemplate pt,
		                                                   TemplateSettings settings)
        {
            //prep the compile unit
            var ccu = new CodeCompileUnit ();
            var namespac = new CodeNamespace (settings.Namespace);
            ccu.Namespaces.Add (namespac);

            var imports = new HashSet<string> ();
            imports.UnionWith (settings.Imports);
            imports.UnionWith (host.StandardImports);
            foreach (string ns in imports)
                namespac.Imports.Add (new CodeNamespaceImport (ns));

            //prep the type
            var type = new CodeTypeDeclaration (settings.Name);
            type.IsPartial = true;
            if (!String.IsNullOrEmpty (settings.Inherits))
                type.BaseTypes.Add (new CodeTypeReference (settings.Inherits));
            else
                type.BaseTypes.Add (new CodeTypeReference (typeof (TextTransformation)));
            namespac.Types.Add (type);

            //prep the transform method
            var transformMeth = new CodeMemberMethod () {
                Name = "TransformText",
                ReturnType = new CodeTypeReference (typeof (String)),
                Attributes = MemberAttributes.Public | MemberAttributes.Override
            };

            //method references that will need to be used multiple times
            var writeMeth = new CodeMethodReferenceExpression (new CodeThisReferenceExpression (), "Write");
            var toStringMeth = new CodeMethodReferenceExpression (new CodeTypeReferenceExpression (typeof (ToStringHelper)), "ToStringWithCulture");
            bool helperMode = false;

            //build the code from the segments
            foreach (TemplateSegment seg in pt.Content) {
                CodeStatement st = null;
                var location = new CodeLinePragma (seg.StartLocation.FileName ?? host.TemplateFile, seg.StartLocation.Line);
                switch (seg.Type) {
                case SegmentType.Block:
                    if (helperMode)
                        //TODO: are blocks permitted after helpers?
                        throw new ParserException ("Blocks are not permitted after helpers", seg.StartLocation);
                    st = new CodeSnippetStatement (seg.Text);
                    break;
                case SegmentType.Expression:
                    st = new CodeExpressionStatement (
                        new CodeMethodInvokeExpression (writeMeth,
                            new CodeMethodInvokeExpression (toStringMeth, new CodeSnippetExpression (seg.Text))));
                    break;
                case SegmentType.Content:
                    st = new CodeExpressionStatement (new CodeMethodInvokeExpression (writeMeth, new CodePrimitiveExpression (seg.Text)));
                    break;
                case SegmentType.Helper:
                    type.Members.Add (new CodeSnippetTypeMember (seg.Text) { LinePragma = location });
                    helperMode = true;
                    break;
                default:
                    throw new InvalidOperationException ();
                }
                if (st != null) {
                    if (helperMode) {
                        //convert the statement into a snippet member and attach it to the top level type
                        //TODO: is there a way to do this for languages that use indentation for blocks, e.g. python?
                        using (var writer = new StringWriter ()) {
                            settings.Provider.GenerateCodeFromStatement (st, writer, null);
                            type.Members.Add (new CodeSnippetTypeMember (writer.ToString ()) { LinePragma = location });
                        }
                    } else {
                        st.LinePragma = location;
                        transformMeth.Statements.Add (st);
                        continue;
                    }
                }
            }

            //complete the transform method
            transformMeth.Statements.Add (new CodeMethodReturnStatement (
                new CodeMethodInvokeExpression (
                    new CodePropertyReferenceExpression (
                        new CodeThisReferenceExpression (),
                        "GenerationEnvironment"),
                        "ToString")));
            type.Members.Add (transformMeth);

            //generate the Host property if needed
            if (settings.HostSpecific) {
                var hostField = new CodeMemberField (new CodeTypeReference (typeof (ITextTemplatingEngineHost)), "hostValue");
                hostField.Attributes = (hostField.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
                type.Members.Add (hostField);

                var hostProp = new CodeMemberProperty () {
                    Name = "Host",
                    Attributes = MemberAttributes.Public,
                    HasGet = true,
                    HasSet = true,
                    Type = hostField.Type
                };
                var hostFieldRef = new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "hostValue");
//.........这里部分代码省略.........
开发者ID:ferrislucas,项目名称:StatefulT4Processor,代码行数:101,代码来源:TemplatingEngine.cs


示例18: CodeSnippetStatementTest

		public void CodeSnippetStatementTest ()
		{
			CodeSnippetStatement css = new CodeSnippetStatement ();
			statement = css;

			Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
				"{0}", NewLine), Generate (), "#1");

			css.Value = "class";
			Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
				"class{0}", NewLine), Generate (), "#2");

			css.Value = null;
			Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
				"{0}", NewLine), Generate (), "#3");
		}
开发者ID:zxlin25,项目名称:mono,代码行数:16,代码来源:CodeGeneratorFromStatementTest.cs


示例19: AddCodeRender

		void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
		{
			if (cr.Code == null || cr.Code.Trim () == "")
				return;

			if (!cr.IsAssign) {
				CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
				parent.RenderMethod.Statements.Add (AddLinePragma (code, cr));
				return;
			}

			CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
			expr.Method = new CodeMethodReferenceExpression (
							new CodeArgumentReferenceExpression ("__output"),
							"Write");

			expr.Parameters.Add (GetWrappedCodeExpression (cr));
			parent.RenderMethod.Statements.Add (AddLinePragma (expr, cr));
		}
开发者ID:nlhepler,项目名称:mono,代码行数:19,代码来源:TemplateControlCompiler.cs


示例20: CodeTryCatchFinallyStatementTest

		public void CodeTryCatchFinallyStatementTest ()
		{
			CodeStatement cs = new CodeGotoStatement ("exit");
			CodeCatchClause ccc1 = new CodeCatchClause ("ex1", new CodeTypeReference ("System.ArgumentException"));
			CodeCatchClause ccc2 = new CodeCatchClause (null, new CodeTypeReference ("System.ApplicationException"));
			CodeSnippetStatement fin1 = new CodeSnippetStatement ("A");
			CodeSnippetStatement fin2 = new CodeSnippetStatement ("B");

			statement = new CodeTryCatchFinallyStatement (new CodeStatement[] { cs },
				new CodeCatchClause[] { ccc1, ccc2 }, new CodeStatement[] { fin1, fin2 });

			Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
				"try {{{0}" +
				"    goto exit;{0}" +
				"}}{0}" +
				"catch (System.ArgumentException ex1) {{{0}" + 
				"}}{0}" +
				"catch (System.ApplicationException ) {{{0}" +
				"}}{0}" +
				"finally {{{0}" +
#if NET_2_0
				"A{0}" +
				"B{0}" +
#else
				"    A{0}" +
				"    B{0}" +
#endif
				"}}{0}", NewLine), Generate (), "#1");

			options.ElseOnClosing = true;

			Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
				"try {{{0}" +
				"    goto exit;{0}" +
				"}} catch (System.ArgumentException ex1) {{{0}" +
				"}} catch (System.ApplicationException ) {{{0}" +
				"}} finally {{{0}" +
#if NET_2_0
				"A{0}" +
				"B{0}" +
#else
				"    A{0}" +
				"    B{0}" +
#endif
				"}}{0}", NewLine), Generate (), "#2");

			statement = new CodeTryCatchFinallyStatement ();

			Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
				"try {{{0}" +
				"}}{0}", NewLine), Generate (), "#3");

			options.ElseOnClosing = false;

			Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
				"try {{{0}" +
				"}}{0}", NewLine), Generate (), "#4");
		}
开发者ID:zxlin25,项目名称:mono,代码行数:58,代码来源:CodeGeneratorFromStatementTest.cs



注:本文中的System.CodeDom.CodeSnippetStatement类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# CodeDom.CodeSnippetTypeMember类代码示例发布时间:2022-05-26
下一篇:
C# CodeDom.CodeSnippetExpression类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap