如何返回指定.NET程序集的公共类和过时类的列表?

How to return the lists of public and obsolete classes for specified .NET assembly?

提问人:NinetyNinth99 提问时间:5/24/2022 最后编辑:NinetyNinth99 更新时间:5/24/2022 访问量:193

问:

该函数应返回公共但过时的类列表

public static IEnumerable<string> GetPublicObsoleteClasses(string assemblyName)
        {
            return Assembly.ReflectionOnlyLoad(assemblyName).GetTypes()
                .Where(x => x.IsClass &&
                            x.IsPublic &&
                            Attribute.GetCustomAttributes(x)
                                .Any(y => y is ObsoleteAttribute))
                .Select(x => x.Name);
        }

但是,它显示此平台不支持 ReflectionOnly 加载

此方法有一个单元测试,不允许更改它

[Test ]
         
        public void GetPublicObsoleteClassesShouldReturnRightList()
        {
            var expected = "CaseInsensitiveHashCodeProvider, ContractHelper, ExecutionEngineException, "+
                           "FirstMatchCodeGroup, IDispatchImplAttribute, PermissionRequestEvidence, "+
                           "SecurityTreatAsSafeAttribute, SetWin32ContextInIDispatchAttribute, "+
                           "UnionCodeGroup, UnmanagedMarshal";

            var obsoleteMembers = CommonTasks.GetPublicObsoleteClasses("mscorlib, Version=4.0.0.0").OrderBy(x=>x);
            var actual = string.Join(", ", obsoleteMembers);
            Assert.AreEqual(expected, actual);
        }
C# 反射 .net-reflector

评论

0赞 John Wu 5/24/2022
此平台不支持 ReflectionOnly 加载显而易见的问题是——你的平台是什么?您在 Windows 上运行吗?
0赞 NinetyNinth99 5/24/2022
@JohnWu是的,Windows 10
0赞 John Wu 5/24/2022
您使用的是 .NET Core 还是 .NET Framework?
0赞 NinetyNinth99 5/24/2022
@JohnWu .NET Core 3.1
0赞 John Wu 5/24/2022
这是 .NET Core 中的已知差距。听起来你应该改用 System.Reflection.TypeLoader

答:

0赞 NightOwl888 5/24/2022 #1

由于您已经引用了 .NET,并且已经加载了它以运行 .NET,因此一个选项是使用 a 而不是字符串来确定要使用的程序集。mscorlibType

[Test]

public void GetPublicObsoleteClassesShouldReturnRightList()
{
    var expected = "CaseInsensitiveHashCodeProvider, ContractHelper, ExecutionEngineException, " +
                   "FirstMatchCodeGroup, IDispatchImplAttribute, PermissionRequestEvidence, " +
                   "SecurityTreatAsSafeAttribute, SetWin32ContextInIDispatchAttribute, " +
                   "UnionCodeGroup, UnmanagedMarshal";

    var obsoleteMembers = CommonTasks.GetPublicObsoleteClasses(typeof(string) /* mscorlib */).OrderBy(x => x);
    var actual = string.Join(", ", obsoleteMembers);
    Assert.AreEqual(expected, actual);
}

public static IEnumerable<string> GetPublicObsoleteClasses(Type typeFromAssembly)
{
    return typeFromAssembly.Assembly.GetTypes()
        .Where(x => x.IsClass &&
                    x.IsPublic &&
                    Attribute.GetCustomAttributes(x)
                        .Any(y => y is ObsoleteAttribute))
        .Select(x => x.Name);
}

评论

0赞 NinetyNinth99 5/24/2022
有没有其他方法可以解决它?因为不建议在单元测试中更改代码
0赞 NightOwl888 5/24/2022
或。我通常不让单元测试依赖外部依赖项来运行,因为缺少外部依赖项时调试需要很长时间,所以我没有其他答案。