今天突发灵感,撰写了这篇文章,希望能为大家带来一些启发。在当今软件开发快速迭代的时代,传统的静态编码模式已逐渐难以满足不断增长的灵活性需求。本文将深入探讨一种结合人工智能、动态编译和反射技术的创新解决方案,揭示编程范式的革命性变革。
这个创新方案主要由三个关键技术组件构成:
C#var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
var chatResult = await chatCompletionService.GetChatMessageContentsAsync(
new ChatHistory
{
new ChatMessageContent(AuthorRole.System, "你是一个C#专家"),
new ChatMessageContent(AuthorRole.User, Prompt)
}
);
这段代码展示了如何利用Semantic Kernel调用AI模型(如DeepSeek)生成代码。关键特点包括:
C#private string ExtractCSharpCode(string input)
{
string[] patterns = new[]
{
@"```csharp\r?\n([\s\S]*?)```",
@"namespace\s+[\w\.]+\s*\{[\s\S]*?\}",
@"public\s+class\s+\w+\s*:\s*\w+\s*\{[\s\S]*?\}"
};
// 使用正则表达式精准提取代码块
}
代码提取机制的亮点:
C#var compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
);
动态编译的关键优势:
C#var pluginTypes = assembly.GetTypes()
.Where(t => t.IsPublic && !t.IsInterface && !t.IsAbstract)
.ToList();
var pluginInstance = Activator.CreateInstance(pluginType) as ISortRules;
pluginInstance.Sort(testList);
插件机制的创新点:
接口
C#using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppDyCode
{
public interface ISortRules
{
public void Sort(List<string> list);
public void Sort(List<int> list);
}
}
动态取得接口原代码
C#using System;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CSharp;
namespace AppDyCode
{
public class InterfaceCodeReader
{
public static string GetInterfaceDefinition(Type interfaceType)
{
// 创建代码提供者
CSharpCodeProvider provider = new CSharpCodeProvider();
// 创建代码生成器选项
CodeGeneratorOptions options = new CodeGeneratorOptions();
// 使用StringWriter捕获生成的代码
using (StringWriter writer = new StringWriter())
{
// 创建CodeCompileUnit
CodeCompileUnit compileUnit = new CodeCompileUnit();
CodeNamespace codeNamespace = new CodeNamespace(interfaceType.Namespace);
compileUnit.Namespaces.Add(codeNamespace);
// 创建接口声明
CodeTypeDeclaration interfaceDeclaration = new CodeTypeDeclaration(interfaceType.Name)
{
IsInterface = true,
TypeAttributes = TypeAttributes.Interface | TypeAttributes.Public
};
// 添加方法
foreach (var method in interfaceType.GetMethods())
{
CodeMemberMethod codeMethod = new CodeMemberMethod
{
Name = method.Name,
ReturnType = new CodeTypeReference(method.ReturnType)
};
// 添加方法参数
foreach (var param in method.GetParameters())
{
codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(param.ParameterType, param.Name));
}
interfaceDeclaration.Members.Add(codeMethod);
}
codeNamespace.Types.Add(interfaceDeclaration);
// 生成代码
provider.GenerateCodeFromCompileUnit(compileUnit, writer, options);
return writer.ToString();
}
}
}
}
辅助工具类
C#using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppDyCode
{
// 自定义 ListBoxItem 类
public class ListBoxItem
{
public string Text { get; set; }
public object Tag { get; set; }
public override string ToString()
{
return Text;
}
}
}
主程序
C#
#pragma warning disable SKEXP0010
using System.Reflection;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
namespace AppDyCode
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void btnLoadPlugins_Click(object sender, EventArgs e)
{
// 创建更安全的Semantic Kernel配置
var kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddOpenAIChatCompletion(
modelId: "deepseek-chat",
apiKey: Environment.GetEnvironmentVariable("DEEPSEEK_API_KEY") ?? "sk-xxxx",
endpoint: new Uri("https://api.deepseek.com/v1")
);
// 构建内核
var kernel = kernelBuilder.Build();
string Prompt = @"
作为一个专业的C#专家,:
用以下接口模板
{interface}继承生成完整的C#代码,完成{requirement},生成代码中不要包括接口模板内容,只需要生成完整的C#代码,其它内容不要给我。
";
string interfaceCode = InterfaceCodeReader.GetInterfaceDefinition(typeof(ISortRules));
Prompt = Prompt.Replace("{interface}", interfaceCode);
Prompt = Prompt.Replace("{requirement}", txtMsg.Text);
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
var chatResult = await chatCompletionService.GetChatMessageContentsAsync(
new ChatHistory
{
new ChatMessageContent(AuthorRole.System, "你是一个C#专家"),
new ChatMessageContent(AuthorRole.User, Prompt)
},
new OpenAIPromptExecutionSettings
{
MaxTokens = 800,
Temperature = 0.6,
TopP = 0.9
}
);
string result = chatResult[0].Content;
var code = ExtractCSharpCode(result);
try
{
// 动态编译代码
var assemblyResult = CompileDynamicAssembly(code);
if (assemblyResult.Success)
{
// 获取动态编译后的程序集
var assembly = assemblyResult.Assembly;
// 查找所有公共类型
var pluginTypes = assembly.GetTypes()
.Where(t => t.IsPublic && !t.IsInterface && !t.IsAbstract)
.ToList();
// 清空并填充 lstPlugins
lstPlugins.Items.Clear();
foreach (var type in pluginTypes)
{
// 创建一个 ListBoxItem,并将类型存储在 Tag 属性中
var item = new ListBoxItem
{
Text = type.FullName,
Tag = type
};
lstPlugins.Items.Add(item);
}
MessageBox.Show($"成功加载 {pluginTypes.Count} 个插件类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
// 显示编译错误
MessageBox.Show(string.Join(Environment.NewLine, assemblyResult.Errors),
"编译错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show($"加载插件时发生错误:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private (bool Success, Assembly Assembly, string[] Errors) CompileDynamicAssembly(string sourceCode)
{
var assemblyName = Path.GetRandomFileName();
var references = new List<MetadataReference>
{
// 基本 .NET 程序集引用
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).Assembly.Location)
};
// 添加 System.Collections 程序集引用
try
{
var systemCollectionsAssembly = Assembly.Load("System.Collections, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
references.Add(MetadataReference.CreateFromFile(systemCollectionsAssembly.Location));
}
catch (Exception ex)
{
// 如果加载失败,可以记录错误或使用备选方案
MessageBox.Show($"无法加载 System.Collections 程序集: {ex.Message}");
}
references.AddRange(new[]
{
// 当前应用程序的程序集引用
MetadataReference.CreateFromFile(Assembly.GetExecutingAssembly().Location),
// 包含 ISortRules 接口的程序集引用
MetadataReference.CreateFromFile(typeof(ISortRules).Assembly.Location),
// 添加 System.Collections.Generic 的引用
MetadataReference.CreateFromFile(typeof(System.Collections.Generic.List<>).Assembly.Location)
});
// 完整的源代码,确保包含必要的 using 语句
string fullSourceCode = $@"
using System;
using System.Collections.Generic;
using {typeof(ISortRules).Namespace};
{sourceCode}";
var syntaxTree = CSharpSyntaxTree.ParseText(fullSourceCode);
var compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
);
using (var ms = new MemoryStream())
{
var result = compilation.Emit(ms);
if (result.Success)
{
ms.Seek(0, SeekOrigin.Begin);
var assembly = Assembly.Load(ms.ToArray());
return (true, assembly, Array.Empty<string>());
}
else
{
var errors = result.Diagnostics
.Where(d => d.Severity == DiagnosticSeverity.Error)
.Select(d => $"{d.Id}: {d.GetMessage()}")
.ToArray();
return (false, null, errors);
}
}
}
private string ExtractCSharpCode(string input)
{
// 使用更复杂的正则表达式,同时支持多种代码块提取
string[] patterns = new[]
{
@"```csharp\r?\n([\s\S]*?)```", // 代码块形式
@"namespace\s+[\w\.]+\s*\{[\s\S]*?\}", // 完整命名空间
@"public\s+class\s+\w+\s*:\s*\w+\s*\{[\s\S]*?\}" // 类定义块
};
foreach (var pattern in patterns)
{
Match match = Regex.Match(input, pattern, RegexOptions.Multiline);
if (match.Success)
{
// 清理代码块,移除代码块标记
string extractedCode = match.Groups[1]?.Value ?? match.Value;
// 确保代码有效性
if (!string.IsNullOrWhiteSpace(extractedCode))
{
// 额外清理:移除前后空白
return extractedCode.Trim();
}
}
}
// 如果没有匹配,尝试最后的备用方案
// 查找第一个看起来像有效的C#代码块
Match fallbackMatch = Regex.Match(input, @"(public\s+class\s+\w+[\s\S]*?})", RegexOptions.Singleline);
if (fallbackMatch.Success)
{
return fallbackMatch.Value.Trim();
}
return string.Empty;
}
private void btnTest_Click(object sender, EventArgs e)
{
if (lstPlugins.SelectedItem == null)
{
MessageBox.Show("请先选择一个插件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
try
{
// 获取选中的插件类型名称
string selectedPluginTypeName = lstPlugins.SelectedItem.ToString();
// 通过反射查找插件类型
var pluginType = (Type)((ListBoxItem)lstPlugins.SelectedItem).Tag;
if (pluginType == null)
{
MessageBox.Show($"未找到类型 {selectedPluginTypeName}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// 检查插件是否实现了 ISortRules 接口
if (!typeof(ISortRules).IsAssignableFrom(pluginType))
{
MessageBox.Show("选择的插件不是有效的排序插件", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// 创建插件实例
var pluginInstance = Activator.CreateInstance(pluginType) as ISortRules;
// 准备测试数据
var testList = txtTest.Text.Split(",").ToList().ConvertAll(x=> {
return int.Parse(x.Trim());
}).ToList();
// 调用排序方法
pluginInstance.Sort(testList);
// 显示排序后的列表
txtResult.Text += string.Join(", ", testList);
}
catch (Exception ex)
{
MessageBox.Show($"插件调用错误:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}


这种技术范式预示着编程模式的重大变革:
我们正站在软件开发的十字路口。这种AI驱动的动态编程范式,不仅仅是一种技术尝试,更代表了未来软件架构的发展方向。
通过将人工智能、动态编译和反射技术巧妙结合,我们正在重新定义"代码"的概念 —— 从静态的文本,转变为可以即时生成、动态调整的智能系统。
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!