如何使用c#代码更改c#项目的类名
本文关键字:项目 何使用 代码 | 更新日期: 2023-09-27 18:18:24
例如,我有一个goodDay.cs
类;我需要使用c#代码将其重命名为badDay.cs
,并且必须确保项目仍然正常工作。
我该怎么做?
可能是这样的:
string solutionFolder = @"C:'Projects'WpfApplication10'WpfApplication10";
string CSName = "Goodday.cs";
string newCSName = "BadDay.cs";
string projectFile = "WpfApplication10.csproj";
File.Move(System.IO.Path.Combine(solutionFolder, CSName), System.IO.Path.Combine(solutionFolder, newCSName));
File.WriteAllText(System.IO.Path.Combine(solutionFolder, projectFile),File.ReadAllText(System.IO.Path.Combine(solutionFolder, projectFile)).Replace(CSName,newCSName));
听起来你想写一个重构工具。这是非常困难的,并且涉及到实现大量的C Sharp编译器。
幸运的是微软最近开放了他们的编译器(并在。net中重写了它)。Roslyn项目目前处于CTP阶段,它将允许你了解c#在做什么,并将帮助你重构代码(像JetBrains这样的公司不得不从头开始编写自己的c#解析器)。
这是我从一篇博客文章中找到的一个例子
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Roslyn.Services;
using Roslyn.Scripting.CSharp;
namespace RoslynSample
{
class Program
{
static void Main(string[] args)
{
RefactorSolution(@"C:'Src'MyApp.Full.sln", "ExternalClient", "ExternalCustomer");
Console.ReadKey();
}
private static void RefactorSolution(string solutionPath, string fileNameFilter, string replacement)
{
var builder = new StringBuilder();
var workspace = Workspace.LoadSolution(solutionPath);
var solution = workspace.CurrentSolution;
if (solution != null)
{
foreach (var project in solution.Projects)
{
var documentsToProcess = project.Documents.Where(d => d.DisplayName.Contains(fileNameFilter));
foreach (var document in documentsToProcess)
{
var targetItemSpec = Path.Combine(
Path.GetDirectoryName(document.Id.FileName),
document.DisplayName.Replace(fileNameFilter, replacement));
builder.AppendFormat(@"tf.exe rename ""{0}"" ""{1}""{2}", document.Id.FileName, targetItemSpec, Environment.NewLine);
}
}
}
File.WriteAllText("rename.cmd", builder.ToString());
}
}
}