gpt4 book ai didi

c# - 从包含类定义的字符串创建动态类

转载 作者:行者123 更新时间:2023-11-30 14:22:49 25 4
gpt4 key购买 nike

我有一个接受表名的存储过程,然后它读取表结构并以字符串中类定义的形式返回表结构。

例如:

string myString = 
"
public class TableName
{
public int Column1 { get; set; }
}
"

是否可以从包含类定义的字符串创建类/类型?例如:-

Type type = GenerateType(myString);

我必须将此类型变量传递给我的其他代码段,因此请帮助我从包含类定义的字符串创建类/类型。

最佳答案

您可以使用 CSharpCodeProvider 在运行时编译您的结果,然后使用 Activator - 类从您生成的代码创建一个对象。

// compile your piece of code to dll file
Microsoft.CSharp.CSharpCodeProvider cSharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters compilerParameters = new System.CodeDom.Compiler.CompilerParameters();
compilerParameters.GenerateInMemory = true;
compilerParameters.GenerateExecutable = false;
System.CodeDom.Compiler.CompilerResults cResult = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, "using System; namespace Tables { 'put here your class definition' }");

// then load your dll file, get type and object from class
Assembly assembly = cResult.CompiledAssembly;
Type myTableType = assembly.GetType("Tables.Tablename");
var finalResult = Activator.CreateInstance(myTableType);

关于c# - 从包含类定义的字符串创建动态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48062438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com