Calling "IsAssignableFrom" from an interface does not return a specific class

I am trying to return a type of a class object that implements the interface defined in the code below.

The linq operator returns only the interface itself, so the console output:

AssignableExperiment.IRule

Why is not a particular class returned?

using System; using System.Linq; namespace AssignableExperiment { public interface IRule { void Validate(string s); } public class ConcreteRule : IRule { public void Validate(string s) { // some logic } } class Program { static void Main(string[] args) { var ruleType = typeof(IRule); var ruleTypes = from t in ruleType.Assembly.GetTypes() where t.IsAssignableFrom(ruleType) select t; foreach (var type in ruleTypes) { Console.WriteLine(type); } Console.ReadLine(); } } } 
+4
source share
2 answers

You have to rotate it around the IsAssignableFrom MSDN . Since IsAssignableFrom works differently, as expected: BaseType.IsAssignableFrom(DerviedType) returns true.

 var ruleTypes = from t in ruleType.Assembly.GetTypes() where ruleType.IsAssignableFrom(t) select t; 

If you do not want to return IRule :

 var ruleTypes = from t in ruleType.Assembly.GetTypes() where ruleType.IsAssignableFrom(t) && t != ruleType select t; 
+7
source

I hate IsAssignableFrom, it's so crudely written.

I always roll back the extension:

 public static bool IsTypeOf<T>(this Type type) { return typeof (T).IsAssignableFrom(type); } 

Using this prevents insidious erroneous execution.

Then you could write:

var ruleTypes = ruleType.Assembly.GetTypes().Where(t=> t.IsTypeOf<IRule>());

+5
source

Source: https://habr.com/ru/post/1381367/


All Articles