簡體   English   中英

是否有任何工具可以讓我將所有C#內置類型更改為其.NET Framework類型?

[英]Are there any tools that allow me to change all C# built-in types to their .NET Framework types?

我發現很難保持一致的一件事是使用int vs Int32bool vs Boolean etcetera。

我發現通過區分大小寫和突出顯示顏色語法更容易識別所有類型...

List<int>

List<Int32>

后者更清潔並堅持一致性。 兩者都有很多代碼,我正在尋找一種可以全部更改的重構工具。

是否有任何工具可以讓我將所有C#內置類型更改為其.NET Framework類型?

如果您查看StyleCop ,規則SA1121實際上會強制執行您想要的相反操作(要求您將Int32更改為int )。 反編譯該規則並創建自己的StyleCop規則以強制執行相反的操作相當簡單。

這不是自動的,但是在您完成初始轉換后,您可以將其合並到構建中,然后將任何新用法標記為錯誤。

使用Roslyn CTP ,實際上可以執行以下操作:

static SyntaxTree UpdatePredefinedTypes(this SyntaxTree tree)
{
    PredefinedTypeSyntax node;
    var root = tree.Root;
    while (null != (node = root.DescendentNodes()
                               .OfType<PredefinedTypeSyntax>()
                               .FirstOrDefault(
                                 syn => redefineMap.ContainsKey(syn.PlainName))))
    {
        var ident = Syntax.IdentifierName(redefineMap[node.PlainName]);
        root = root.ReplaceNode<SyntaxNode, SyntaxNode>(
            node, 
            ident.WithLeadingTrivia(node.GetLeadingTrivia())
                 .WithTrailingTrivia(node.GetTrailingTrivia()));
    }

    return SyntaxTree.Create(
        tree.FileName,
        (CompilationUnitSyntax)root,
        tree.Options);
}

當使用適當的redefineMap (例如{"int","Int32"}{"double","Double"} )時,以下程序已成功轉換:

using System;
namespace HelloWorld {
    class Program {
        static void Main(string[] args) {
            int x = Int32.Parse("11");
            double y = x;
            Console.WriteLine("Hello, World! {0}", y);
        }
     }
}

輸出:

using System;
namespace HelloWorld {
    class Program {
        static void Main(String[] args) {
            Int32 x = Int32.Parse("11");
            Double y = x;
            Console.WriteLine("Hello, World! {0}", y);
        }
     }
}

編譯時:

var mscorlib = new AssemblyFileReference(
    typeof(object).Assembly.Location);

var newTree = UpdatePredefinedTypes(tree);

var compilation = Compilation.Create("HelloWorld")
                             .AddReferences(mscorlib)
                             .AddSyntaxTrees(new[] { newTree });
var results = compilation.Emit(File.Create("helloworld.exe"));
Console.WriteLine("Success: {0}", results.Success);
foreach (var message in results.Diagnostics)
{
    Console.WriteLine("{0}", message);
}
// C:\tmp\cs>roslyn-test.exe
// Success: True
// 
// C:\tmp\cs>dir /b *.exe
// roslyn-test.exe
// helloworld.exe
//
// C:\tmp\cs>helloworld.exe
// Hello, World! 11
//

您甚至可以利用Workspace功能來更新整個解決方案:

var workspace = Workspace.LoadSolution(info.FullName);
var solution = workspace.CurrentSolution;
foreach (var project in solution.Projects
    .Where(prj => prj.LanguageServices.Language == "C#"))
{
    foreach (var doc in project.Documents
        .Where(d => d.SourceCodeKind == SourceCodeKind.Regular
                 && d.LanguageServices.Language == "C#"))
    {
        var tree = SyntaxTree.ParseCompilationUnit(
            doc.GetText(),
            doc.DisplayName);
        var newTree = UpdatePredefinedTypes(tree);

        solution = solution.UpdateDocument(doc.Id, newTree.Text);
    }
}

workspace.ApplyChanges(workspace.CurrentSolution, solution);
// when running this in VS on itself it correctly updates the project!

除了VS的搜索和替換功能外,我不知道其他任何工具。

當我調用靜態成員時,通常將c#別名用於類型聲明和.NET類型。

int i = Int32.Parse(s);

這只是個人喜好。

我最終寫了一個宏來做到這一點

Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics

Public Module ReplaceCSharpBuiltInTypesWithTheirFrameworkTypes
    Sub ReplaceCSharpBuiltInTypesWithTheirFrameworkTypes()
        Dim dictionary As New Collections.Generic.Dictionary(Of String, String)
        dictionary.Add("bool", "Boolean")
        dictionary.Add("byte", "Byte")
        dictionary.Add("sbyte", "SByte")
        dictionary.Add("char", "Char")
        dictionary.Add("decimal", "Decimal")
        dictionary.Add("double", "Double")
        dictionary.Add("float", "Single")
        dictionary.Add("int", "Int32")
        dictionary.Add("uint", "UInt32")
        dictionary.Add("long", "Int64")
        dictionary.Add("ulong", "UInt64")
        dictionary.Add("object", "Object")
        dictionary.Add("short", "Int16")
        dictionary.Add("ushort", "UInt16")
        dictionary.Add("string", "String")
        For Each key In dictionary.Keys
            DTE.Find.FindWhat = key
            DTE.Find.ReplaceWith = dictionary(key)
            DTE.Find.Target = vsFindTarget.vsFindTargetCurrentDocument
            DTE.Find.MatchCase = True
            DTE.Find.MatchWholeWord = True
            DTE.Find.MatchInHiddenText = False
            DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral
            DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResultsNone
            DTE.Find.Action = vsFindAction.vsFindActionReplaceAll
            DTE.Find.Execute()
        Next
    End Sub
End Module

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM