Calling 'IsAssignableFrom' from an interface doesn't return the concrete class

孤街醉人 提交于 2019-12-08 19:26:54

问题


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

The linq statement only returns the interface itself, and so the console output is just:

AssignableExperiment.IRule

Why isn't the concrete class being 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();
        }
    }
}

回答1:


You should turn it around the IsAssignableFrom MSDN. Because IsAssignableFrom works another way around as expected: BaseType.IsAssignableFrom(DerviedType) returns true.

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

If you don't want to get back IRule:

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



回答2:


I hate the IsAssignableFrom, it is so nefariously written.

I always roll the extension:

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

Using this prevents insidious errant execution.

Then you could write:

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



来源:https://stackoverflow.com/questions/8142485/calling-isassignablefrom-from-an-interface-doesnt-return-the-concrete-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!