Finding everywhere an enum is converted to string

蹲街弑〆低调 提交于 2019-12-03 16:37:07

问题


I'm currently trying to find everywhere in a solution where a specific enum is converted to a string, whether or not ToString() is explicitly called. (These are being replaced with a conversion using enum descriptions to improve obfuscation.)

Example: I'd like to find code such as string str = "Value: " + SomeEnum.someValue;

I've tried replacing the enum itself with a wrapper class containing implicit conversions to the enum type and overriding ToString() in the wrapper class, but when I try searching for uses of the ToString() override it gives me a list of places in the solution where ToString() is called on anything (and only where it is called explicitly). The search was done with ReSharper in Visual Studio.

Is there another way to find these enum-to-string conversions? Going through the entire solution manually doesn't sound like much fun.


回答1:


The trick in Roslyn is to use SemanticModel.GetTypeInfo() and then check the ConvertedType to find these sort of implicit conversions.

A complete example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;
using Roslyn.Services;
using Roslyn.Services.CSharp;
using Roslyn.Compilers.Common;

class Program
{
    static void Main(string[] args)
    {
        var code = @"enum E { V } class { static void Main() { string s = ""Value: "" + E.V; } }";
        var doc = Solution.Create(SolutionId.CreateNewId())
            .AddCSharpProject("foo", "foo")
            .AddMetadataReference(MetadataFileReference.CreateAssemblyReference("mscorlib"))
            .AddDocument("doc.cs", code);
        var stringType = doc.Project.GetCompilation().GetSpecialType(SpecialType.System_String);
        var e = doc.Project.GetCompilation().GlobalNamespace.GetTypeMembers("E").Single();
        var v = e.GetMembers("V").Single();
        var refs = v.FindReferences(doc.Project.Solution);
        var toStrings = from referencedLocation in refs
                        from r in referencedLocation.Locations
                        let node = GetNode(doc, r.Location)
                        let convertedType = doc.GetSemanticModel().GetTypeInfo(GetNode(doc, r.Location)).ConvertedType
                        where convertedType.Equals(stringType)
                        select r.Location;
        foreach (var loc in toStrings)
        {
            Console.WriteLine(loc);
        }
    }

    static CommonSyntaxNode GetNode(IDocument doc, CommonLocation loc)
    {
        return loc.SourceTree.GetRoot().FindToken(loc.SourceSpan.Start).Parent.Parent.Parent;
    }
}


来源:https://stackoverflow.com/questions/15891197/finding-everywhere-an-enum-is-converted-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!