有没有办法告诉代码中的其他地方是否使用了字符串/ guid?

时间:2018-01-11 07:33:09

标签: c#

假设我有一个文件已满,如果guids我想检查它们是否已经在代码中的某处使用过:

public static Guid GenericGuidName{ get { return new Guid("2b1bd512-6d75-4c63-9e2e-dfebda4f4393"); } }

有没有办法,除了ctrl + f-ing每个guid的整个解决方案?

1 个答案:

答案 0 :(得分:1)

假设使用您提供的代码模式公开了所有GUID,您可以找到所有这些GUID并将它们放在字典中,并带有一点反射。

class MysteryCode
{
    public static Guid Foo { get { return new Guid("2b1bd512-6d75-4c63-9e2e-dfebda4f4393"); } }
    public static Guid Bar { get { return new Guid("2b1bd512-6d75-4c63-9e2e-dfebda4f4394"); } }
}

public class Program
{
    public static Dictionary<Guid, PropertyInfo> FindGuids()
    {
        return System.Reflection.Assembly.GetExecutingAssembly()
            .GetTypes()
            .SelectMany
            (
                t => t.GetProperties
                (
                    BindingFlags.Static | BindingFlags.Public
                )
            )
            .Where
            (
                p => p.PropertyType == typeof(Guid)
            )
            .ToDictionary
            (
                p => (Guid)p.GetValue(null),
                p => p
            );
    }

    public static void Main()
    {
        var dictionary = Program.FindGuids();

        foreach (var g in dictionary)
        {
            Console.WriteLine("{0} {1}.{2}", g.Key, g.Value.DeclaringType.FullName, g.Value.Name);
        }
    }
}

输出:

2b1bd512-6d75-4c63-9e2e-dfebda4f4393 Example.MysteryCode.Foo
2b1bd512-6d75-4c63-9e2e-dfebda4f4394 Example.MysteryCode.Bar

Working example on DotNetFiddle

相关问题