Vladislav Hromyh Vladislav Hromyh - 1 year ago 43
C# Question

Get Interfaces but not the base one

Here is little problem.

I have interface "ISuperAbility".
And I have some superAbilities(also interfaces) which inherited from ISuperAbility.

So, I have a dictionary with a Type as a key, and double(points) as a Value.
In that dictionary I have next data:

abilityPoints = new Dictionary<Type, double>();
abilityPoints.Add(typeof(IFlyable), 2.0f);
abilityPoints.Add(typeof(IInvisible), 4.0f);
abilityPoints.Add(typeof(IMindsReadable), 6.0f);
abilityPoints.Add(typeof(IWallWalkable), 1.0f);

All these "abilities" is a interfaces that inheried from ISuperAbility.

Then, I have hero, for example "Mysterio", that implements two interfaces:

SO, when I want to get all points on certain hero, I do the next thing:

public static double ForceOfHuman(Human hero)
double force = 0;

Type[] humanInterfaces = hero.GetType().GetInterfaces();

foreach (Type humanInterface in humanInterfaces)
if (humanInterface.IsAssignableFrom(typeof(ISuperAbility)))
force += XMenLaboratory.abilityPoints[humanInterface];

return force;

And after this I have an exception that tell me about problem cause dictionary does not have such a key. And a key is "ISuperAbility".

So that search in method return also a base interface. Is it normal ? I think, more than that.

So, what can I do for getting interfaces except base one ?


I must say, that I was wrong at certain moment.
My abilities that inheried from ISuperAbility does not reach this condition

if (humanInterface.IsAssignableFrom(typeof(ISuperAbility)))
force += XMenLaboratory.abilityPoints[humanInterface];


Solution, that I prefered was a next one:

if (typeof(ISuperAbility).IsAssignableFrom(humanInterface) && humanInterface != typeof(ISuperAbility))
force += XMenLaboratory.abilityPoints[humanInterface];

Tank you all.

Answer Source

You can exclude interface ISuperAbility from your foreach statement:

foreach (Type humanInterface in humanInterfaces.Where(i => i != typeof(ISuperAbility)))

This way you will get all ability interfaces, except for ISuperAbility.