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

C# CodeTypeParameter类代码示例

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

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



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

示例1: Main

//引入命名空间
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Collections.Generic;
namespace System.CodeDom
{
    class CodeDomGenericsDemo
    {
        static void Main()
        {
            try
            {
                CreateGenericsCode("cs", "Generic.cs", "GenericCS.exe");
            }
            catch (Exception e)
            {
                LogMessage("Unexpected Exception:" + e.ToString());
            }
        }

        static void CreateGenericsCode(string providerName, string sourceFileName, string assemblyName)
        {

            CodeDomProvider provider = CodeDomProvider.CreateProvider(providerName);

            LogMessage("Building CodeDOM graph...");

            CodeCompileUnit cu = new CodeCompileUnit();

            CreateGraph(provider, cu);

            StringWriter sw = new StringWriter();

            LogMessage("Generating code...");
            provider.GenerateCodeFromCompileUnit(cu, sw, null);

            string output = sw.ToString();
            output = Regex.Replace(output, "Runtime Version:[^\r\n]*",
                "Runtime Version omitted for demo");

            LogMessage("Dumping source...");
            LogMessage(output);

            LogMessage("Writing source to file...");
            Stream s = File.Open(sourceFileName, FileMode.Create);
            StreamWriter t = new StreamWriter(s);
            t.Write(output);
            t.Close();
            s.Close();

            CompilerParameters opt = new CompilerParameters(new string[]{
                                      "System.dll", 
                                      "System.Xml.dll",
                                      "System.Windows.Forms.dll",
                                      "System.Data.dll",
                                      "System.Drawing.dll"});
            opt.GenerateExecutable = false;
            opt.TreatWarningsAsErrors = true;
            opt.IncludeDebugInformation = true;
            opt.GenerateInMemory = true;

            CompilerResults results;

            LogMessage("Compiling with " + providerName);
            results = provider.CompileAssemblyFromFile(opt, sourceFileName);

            OutputResults(results);
            if (results.NativeCompilerReturnValue != 0)
            {
                LogMessage("");
                LogMessage("Compilation failed.");
            }
            else
            {
                LogMessage("");
                LogMessage("Demo completed successfully.");
            }
            File.Delete(sourceFileName);
        }

        // Create a CodeDOM graph.
        static void CreateGraph(CodeDomProvider provider, CodeCompileUnit cu)
        {
            if (!provider.Supports(GeneratorSupport.GenericTypeReference |
               GeneratorSupport.GenericTypeDeclaration))
            {
                // Return if the generator does not support generics.
                return;
            }

            CodeNamespace ns = new CodeNamespace("DemoNamespace");
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            cu.Namespaces.Add(ns);

            // Declare a generic class.
            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            class1.Name = "MyDictionary";
            class1.BaseTypes.Add(new CodeTypeReference("Dictionary",
                                      new CodeTypeReference[] {
                                          new CodeTypeReference("TKey"),    
                                          new CodeTypeReference("TValue"),    
                                     }));
            CodeTypeParameter kType = new CodeTypeParameter("TKey");
            kType.HasConstructorConstraint = true;
            kType.Constraints.Add(new CodeTypeReference(typeof(IComparable)));
            kType.CustomAttributes.Add(new CodeAttributeDeclaration(
                "System.ComponentModel.DescriptionAttribute",
                    new CodeAttributeArgument(new CodePrimitiveExpression("KeyType"))));

            CodeTypeReference iComparableT = new CodeTypeReference("IComparable");
            iComparableT.TypeArguments.Add(new CodeTypeReference(kType));

            kType.Constraints.Add(iComparableT);

            CodeTypeParameter vType = new CodeTypeParameter("TValue");
            vType.Constraints.Add(new CodeTypeReference(typeof(IList<System.String>)));
            vType.CustomAttributes.Add(new CodeAttributeDeclaration(
                "System.ComponentModel.DescriptionAttribute",
                    new CodeAttributeArgument(new CodePrimitiveExpression("ValueType"))));

            class1.TypeParameters.Add(kType);
            class1.TypeParameters.Add(vType);

            ns.Types.Add(class1);

            // Declare a generic method.
            CodeMemberMethod printMethod = new CodeMemberMethod();
            CodeTypeParameter sType = new CodeTypeParameter("S");
            sType.HasConstructorConstraint = true;
            CodeTypeParameter tType = new CodeTypeParameter("T");
            sType.HasConstructorConstraint = true;

            printMethod.Name = "Print";
            printMethod.TypeParameters.Add(sType);
            printMethod.TypeParameters.Add(tType);

            printMethod.Statements.Add(ConsoleWriteLineStatement(
                new CodeDefaultValueExpression(new CodeTypeReference("T"))));
            printMethod.Statements.Add(ConsoleWriteLineStatement(
                new CodeDefaultValueExpression(new CodeTypeReference("S"))));

            printMethod.Attributes = MemberAttributes.Public;
            class1.Members.Add(printMethod);

            CodeTypeDeclaration class2 = new CodeTypeDeclaration();
            class2.Name = "Demo";

            CodeEntryPointMethod methodMain = new CodeEntryPointMethod();

            CodeTypeReference myClass = new CodeTypeReference(
                "MyDictionary",
                new CodeTypeReference[] {
                    new CodeTypeReference(typeof(int)),
                    new CodeTypeReference("List", 
                       new CodeTypeReference[] 
                            {new CodeTypeReference("System.String") })});

            methodMain.Statements.Add(
                  new CodeVariableDeclarationStatement(myClass,
                      "dict",
                          new CodeObjectCreateExpression(myClass)));

            methodMain.Statements.Add(ConsoleWriteLineStatement(
                new CodePropertyReferenceExpression(
                      new CodeVariableReferenceExpression("dict"),
                            "Count")));

            methodMain.Statements.Add(new CodeExpressionStatement(
                 new CodeMethodInvokeExpression(
                      new CodeMethodReferenceExpression(
                         new CodeVariableReferenceExpression("dict"),
                             "Print",
                                 new CodeTypeReference[] {
                                    new CodeTypeReference("System.Decimal"),
                                       new CodeTypeReference("System.Int32"),}),
                                           new CodeExpression[0])));

            string dictionaryTypeName = typeof(System.Collections.Generic.Dictionary<int,
                System.Collections.Generic.List<string>>[]).FullName;

            CodeTypeReference dictionaryType = new CodeTypeReference(dictionaryTypeName);
            methodMain.Statements.Add(
                  new CodeVariableDeclarationStatement(dictionaryType, "dict2",
                     new CodeArrayCreateExpression(dictionaryType, new CodeExpression[1] { new CodePrimitiveExpression(null) })));

            methodMain.Statements.Add(ConsoleWriteLineStatement(
                           new CodePropertyReferenceExpression(
                                new CodeVariableReferenceExpression("dict2"),
                                        "Length")));

            class2.Members.Add(methodMain);
            ns.Types.Add(class2);
        }

        static CodeStatement ConsoleWriteLineStatement(CodeExpression exp)
        {
            return new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                   new CodeMethodReferenceExpression(
                       new CodeTypeReferenceExpression(new CodeTypeReference("Console")),
                           "WriteLine"),
                               new CodeExpression[]{
                                   exp,
                                     }));
        }

        static CodeStatement ConsoleWriteLineStatement(string text)
        {
            return ConsoleWriteLineStatement(new CodePrimitiveExpression(text));
        }
        static void LogMessage(string text)
        {
            Console.WriteLine(text);
        }

        static void OutputResults(CompilerResults results)
        {
            LogMessage("NativeCompilerReturnValue=" +
                results.NativeCompilerReturnValue.ToString());
            foreach (string s in results.Output)
            {
                LogMessage(s);
            }
        }
    }
}
// This example generates the following code:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version omitted for demo
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

//namespace DemoNamespace
//{
//    using System;
//    using System.Collections.Generic;


//    public class MyDictionary<[System.ComponentModel.DescriptionAttribute("KeyType")]  TKey,
//          [System.ComponentModel.DescriptionAttribute("ValueType")]  TValue> : Dictionary<TKey, TValue>
//        where TKey : System.IComparable, IComparable<TKey>, new()
//        where TValue : System.Collections.Generic.IList<string>
//    {

//        public virtual void Print<S, T>()
//            where S : new()
//        {
//            Console.WriteLine(default(T));
//            Console.WriteLine(default(S));
//        }
//    }

//    public class Demo
//    {

//        public static void Main()
//        {
//            MyDictionary<int, List<string>> dict = new MyDictionary<int, List<string>>();
//            Console.WriteLine(dict.Count);
//            dict.Print<decimal, int>();
//            System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[] dict2 =
//              new System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[] { null };
//            Console.WriteLine(dict2.Length);
//        }
//    }
//}
开发者ID:.NET开发者,项目名称:System.CodeDom,代码行数:278,代码来源:CodeTypeParameter



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# CodeTypeReference类代码示例发布时间:2022-05-24
下一篇:
C# CodeTypeOfExpression类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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