首页 > 解决方案 > CSharpCodeProvider 中的属性

问题描述

我尝试编译一些使用自己的属性的简单代码(ac# 类)。如果我的类属性不使用自定义属性,CSharpCodeCompiler 不会引发错误。

这是我的字符串:

string _string = @"
using System;
using System.Collections.Generic;

namespace Generator
{
    public class ExampleClass
    {
        public int id { get; set; }

    }
}"

        var csc = new CSharpCodeProvider();
        var cc = csc.CreateCompiler();
        CompilerParameters cp = new CompilerParameters();

        cp.ReferencedAssemblies.Add("mscorlib.dll");
        cp.ReferencedAssemblies.Add("System.dll");
        cp.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll");
        cp.ReferencedAssemblies.Add("System.ComponentModel.dll");
        cp.ReferencedAssemblies.Add("System.Runtime.InteropServices.dll");
        cp.ReferencedAssemblies.Add(typeof(GUID).Assembly.Location);

        CompilerResults results = csc.CompileAssemblyFromSource(cp, _string);
        System.Reflection.Assembly _assembly = results.CompiledAssembly;
        Type[] _types = _assembly.GetTypes();
        Type eType = _assembly.GetType(namespaceAndClass);

它是用上面的代码完美编译的。但是如果我使用我的自定义属性,它会抛出一个错误。

我的属性类:

using System;

namespace Generator
{
    [AttributeUsage(AttributeTargets.All)]
    class GUID : Attribute
    {
        private string guid { get; set; }

        public GUID()
        {
            this.guid = Guid.NewGuid().ToString();
        }

        public GUID(string value)
        {
            this.guid = value;
        }

        public string getGuid()
        {
            return guid;
        }
    }
}

我需要用我的自定义属性编译字符串... [GUID()] public int id { get; 放; }

当我尝试这个时,我得到这个错误:异常抛出:mscorlib.dll中的'System.IO.FileNotFoundException'

标签: c#compilationcsharpcodeprovider

解决方案


推荐阅读