'How to return the lists of public and obsolete classes for specified .NET assembly?
The function should return a list of public but obsolete classes
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);
}
However, it shows that ReflectionOnly loading is not supported on this platform.
There is a Unit Test for this method and it is not allowed to change it
[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);
}
Solution 1:[1]
Since you are already referencing mscorlib
and it is already loaded to run .NET, one option is to use a Type
rather than a string to determine what assembly to use.
[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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | NightOwl888 |