不确定为什么这不起作用,基本上这是我的代码:
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = @"C:\myclass.dll";
string code = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
namespace First
{
public class B
{
public List<string> list = new List<string>();
[DisplayName(""Pos""),Category(""Test""),DefaultValue(0),DefaultValueAttribute(0)]
public int Position { get; set; }
}
}
";
CompilerResults r = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(parameters, code);
var DLL = Assembly.LoadFile(parameters.OutputAssembly);
foreach (Type type in DLL.GetExportedTypes())
{
dynamic c = Activator.CreateInstance(type);
_props.SelectedObject = c;
}
将类加载到属性网格中工作正常但属性被忽略,任何想法为什么?并且有解决方案吗?
答案 0 :(得分:1)
首先,你的代码甚至不能为我编译。它需要一些改变。
System.dll
DefaultValue
属性,您需要将其删除很难相信你得到用这段代码编译的程序集。我已经更新了代码,它按预期工作。
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = @"C:\myclass.dll";
parameters.ReferencedAssemblies.Add("System.dll");//Add reference
string code = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
namespace First
{
public class B
{
public List<string> list = new List<string>();
[DisplayName(""Pos""),Category(""Test""),DefaultValue(0)]
public int Position { get; set; }
}
}
";
CompilerResults r = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(parameters, code);
if (r.Errors.Count <= 0)
{
var DLL = Assembly.LoadFile(parameters.OutputAssembly);
foreach (Type type in DLL.GetExportedTypes())
{
dynamic c = Activator.CreateInstance(type);
_props.SelectedObject = c;
}
}