There are a few other questions concerning this on SO, but I felt none of them really provided a solid answer.
I'm messing around with reflection a lot lately, and I wanted to check for types contained within a few assemblies that implement a certain interface.
So I have a class called BESCollector that implements ICollector
public class BESCollector : ICollector
{
// ...
}
Here I load the assembly, loop through all types and see if that type contains an interface of type ICollector...
Assembly pluginAssembly = Assembly.ReflectionOnlyLoadFrom(pluginConfig.AssemblyLocation);
IEnumerable<Type> types = pluginAssembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(ICollector)));
... which yields no results :(. While debugging I can clearly see that it DOES contain this type. I break on the if-loop
Assembly pluginAssembly = Assembly.ReflectionOnlyLoadFrom(pluginConfig.AssemblyLocation);
IEnumerable<Type> types = pluginAssembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(ICollector)));
foreach (Type type in pluginAssembly.GetTypes())
{
Type[] interfaces = type.GetInterfaces();
if (interfaces.Contains(typeof(ICollector)))
{
Console.WriteLine(@"\o/");
}
}
These results are straight from the debugger. Here you can see that interfaces
contains a single Type, namely ICollector:
- interfaces {System.Type[1]} System.Type[]
+ [0] {Name = "ICollector" FullName = "SquidReports.DataCollector.Interface.ICollector"} System.Type {System.ReflectionOnlyType}
And the Type I'm calling .GetInterfaces()
on is clearly BESCollector:
+ type {Name = "BESCollector" FullName = "SquidReports.DataCollector.Plugin.BES.BESCollector"} System.Type {System.ReflectionOnlyType}
But the equality statement interfaces.Contains(typeof(ICollector))
never evaluates to true.
Just so you think I'm not mixing up types here, when I mouse over (typeof(ICollector))
while debugging, it clearly displays SquidReports.DataCollector.Interface.ICollector
.
This, of course, does work:
Type[] interfaces = type.GetInterfaces();
if (interfaces.Any(t => t.Name == typeof(ICollector).Name))
{
Console.WriteLine(@"\o/");
}
But that does't tell me a whole lot, besides the fact that the types of the same name.
Moreover, why does this check fail?
if (typeof(ICollector).Equals(typeof(ICollector)))
{
Console.WriteLine("EQUALIZED");
}
Why does my first equality check fail? More specifically, how does type equality work in C# 5.0? Was there nothing specific implemented for .Equals() for the 'Type' type?
Aucun commentaire:
Enregistrer un commentaire