Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 呼叫';可从';从一个接口不';t返回具体类_C#_Inheritance_.net 4.0 - Fatal编程技术网

C# 呼叫';可从';从一个接口不';t返回具体类

C# 呼叫';可从';从一个接口不';t返回具体类,c#,inheritance,.net-4.0,C#,Inheritance,.net 4.0,我试图返回实现下面代码中定义的接口的类的对象类型 linq语句只返回接口本身,因此控制台输出仅为: 可分配实验 为什么不返回具体类 using System; using System.Linq; namespace AssignableExperiment { public interface IRule { void Validate(string s); } public class ConcreteRule : IRule {

我试图返回实现下面代码中定义的接口的类的对象类型

linq语句只返回接口本身,因此控制台输出仅为:

可分配实验

为什么不返回具体类

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();
        }
    }
}

您应该将其转到
IsAssignableFrom
。因为
IsAssignableFrom
的工作方式与预期不同:
BaseType.IsAssignableFrom(DerviedType)
返回true

var ruleTypes = from t in ruleType.Assembly.GetTypes()
                            where ruleType.IsAssignableFrom(t)
                            select t;
如果您不想返回
IRule

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

我讨厌这封信,它写得太邪恶了

我总是滚动分机:

public static bool IsTypeOf<T>(this Type type)
{
    return typeof (T).IsAssignableFrom(type);
}
publicstaticboolistypeof(此类型)
{
返回类型为(T)。IsAssignableFrom(类型);
}
使用它可以防止潜在的错误执行

然后你可以写:


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

现在我的项目中只有一个地方需要它,所以我将省略通用帮助程序,谢谢你的回答。