如何体现的接口类型 在运行时(How to reflect an interfaced typ

2019-10-28 14:08发布

我有多个数据点和相关联的数据处理器,用于每个。

public interface IDataPointProcessor<T> where T : DataPointInputBase
{
    DataPointOutputBase GetOutput(T input);
}

我从文件中加载数据点的名单,并希望利用其单相关的处理器来处理它们。

foreach (DataPointInputBase item in input.DataPoints)
{
    //assuming item coming in is of type 'X' how do I get correct processor
    var type = typeof(IDataPointProcessor<X>);
    var types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(s => s.GetTypes())
                .Where(p => type.IsAssignableFrom(p) && !p.IsAbstract);

    IDataPointProcessor<X> matchedType = ??

}

如何解决“X”,所以我可以实例并处理输入?

更新#1自光荣和幸运的结合从下面的答案,我得到以下,但它抛出一个异常- “对象不匹配目标类型” 尽管这一切似乎匹配OK的调试器。 是有可能铸造为IDataPointProcessor <>和调用接口方法清洁,即:instance.GetOutput(项目);

foreach (DataPointInputBase item in input.DataPoints)
{
    Type typeGenArg = item.GetType();

    Type typeInterfaceGen = typeof(IDataPointProcessor<>).MakeGenericType(typeGenArg);

    Type type = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(x => x.GetTypes())
        .Where(x => typeInterfaceGen.IsAssignableFrom(x) && !x.IsAbstract)
        .FirstOrDefault();

    Type genericType = typeof(IDataPointProcessor<>);

    Type dependedGenericType = genericType.MakeGenericType(typeof(DataPointInputBase));

    var method = dependedGenericType.GetMethod("GetOutput");
    var instance = Activator.CreateInstance(type);
    //currently throws:System.Reflection.TargetException: 'Object does not match target type.'
    var result = method.Invoke(instance, new object[] { item });
    //Ideally I want to do this and avoid the magic strings etc
    //var temp_output = instance.GetOutput(item);
}

更新#2为了保持运动,我硬编码类型“Age_Input”来验证事情的作品。 我缺少动态调用硬编码位?

我应该能够投实例IDataPointProcessor<IDataPointInput>并调用GetOutput()的界面上

foreach (IDataPointInput item in input.DataPoints)
{
    Type typeGenArg = item.GetType();

    Type typeInterfaceGen = typeof(IDataPointProcessor<>).MakeGenericType(typeGenArg);

    Type type = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(x => x.GetTypes())
        .Where(x => typeInterfaceGen.IsAssignableFrom(x) && !x.IsAbstract)
        .FirstOrDefault();

    Type genericType = typeof(IDataPointProcessor<>);

    Type dependedGenericType = genericType.MakeGenericType(typeof(IDataPointInput));

    var instance = Activator.CreateInstance(type);

    if (instance is IDataPointProcessor<Age_Input>)//hard-coded
    {
        var processor = instance as IDataPointProcessor<Age_Input>;
        Age_Input temp = item as Age_Input;
        var result = processor.GetOutput(temp);
    }
    if (instance is DataPointProcessorBase<DataPointInputBase>)
    {
        //false
    }
    if (instance is IDataPointProcessor<DataPointInputBase>)
    {
        //false
    }
    if (instance is IDataPointProcessor<IDataPointInput>)
    {
        //false - shouldn't this work?
    }
}

Age_Input是一个很小的类,从一个哑基类和一个空的接口继承

public class Age_Input : DataPointInputBase, IDataPointInput
{
    public int AgeExact { get; set; }
} 

public class DataPointInputBase : IDataPointInput
{
}
public interface IDataPointInput
{
}

处理器级是同样简单

 public abstract class DataPointProcessorBase<T> : IDataPointProcessor<T> where T : IDataPointInput, new()
    {
        //public abstract DataPointOutputBase GetOutput(DataPointInputBase input);
        public abstract DataPointOutputBase GetOutput(T input);
    }

    public interface IDataPointInput
    {
    }

    public interface IDataPointProcessor<IDataPointInput> 
    {
        DataPointOutputBase GetOutput(IDataPointInput input);
    }

Answer 1:

首先,你应该让你的协变界面这个样子。

public interface IDataPointProcessor<in T> where T : DataPointInputBase
{
    DataPointOutputBase GetOutput(T input);
}

你应该获取由执行类型IDataPointProcessor<>那么您应该创建检索类型的实例并调用泛型类型的方法。

Type genericType = typeof(IDataPointProcessor<>);
var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(p => genericType.IsAssignableFrom(p) && !p.IsAbstract).ToList();


var dependedGenericType = genericType.MakeGenericType(typeof(DataPointInputBase));
var method = dependedGenericType.GetMethod("GetOutput");
var instance = Activator.CreateInstance(types[0]);
method.Invoke(instance, new object[] { new DataPointInputBase() });


Answer 2:

因此,作为在通常情况下,如果你能避免思考你通常更好。 我交易代码味道的一点点的更简单的解决方案。

从本质上讲,我回到基础知识和使用哑接口,并在返回的相应处理器的底漆的实例输入一个辅助方法。

现在,我的大反射循环替换为:

foreach (IDataPointInput item in input)
{
    IDataPointProcessor processor = item.GetProcessor();
    IDataPointOutput output = processor.GetOutput();
}

该代码味道是这样的 - 不是一个问题

public override IDataPointProcessor GetProcessor()
{
    return new Age_Processor(this);
}

下面的完整代码

#region Interfaces
public interface IDataPointProcessor
{
    IDataPointOutput GetOutput();
}

public interface IDataPointInput
{
    IDataPointProcessor GetProcessor();
}

public interface IDataPointOutput
{
    List<string> DebugStrings { get; set; }
} 
#endregion

#region Base Classes
public abstract class DataPointProcessorBase : IDataPointProcessor
{
    public abstract IDataPointOutput GetOutput();
}

public abstract class DataPointInputBase : IDataPointInput
{
    public abstract IDataPointProcessor GetProcessor();
}

public abstract class DataPointOutputBase : IDataPointOutput
{
    public List<string> DebugStrings { get; set; }

    public DataPointOutputBase()
    {
        DebugStrings = new List<string>();
    }
} 
#endregion

public class Age_Output : DataPointOutputBase
{
}

public class Age_Input : DataPointInputBase
{
    public int AgeExact { get; set; }

    public override IDataPointProcessor GetProcessor()
    {
        return new Age_Processor(this);
    }
}

public class Age_Processor : DataPointProcessorBase
{
    public Age_Input Input { get; set; }
    public Age_Processor(Age_Input input)
    {
        Input = input;
    }

    public override IDataPointOutput GetOutput()
    {
        Age_Output output = new Age_Output();


        if (Input.AgeExact > 30)
        {
            output.DebugStrings.Add("Getting old");
        }
        else
        {
            output.DebugStrings.Add("Still young");
        }
        return output;
    }
}

public class DecisionEngine
{
    public void GetDecisions()
    {
        List<IDataPointInput> input = new List<IDataPointInput>();
        input.Add(new Age_Input { AgeExact = 44 });
        foreach (IDataPointInput item in input)
        {
            IDataPointProcessor processor = item.GetProcessor();
            IDataPointOutput output = processor.GetOutput();

        }
    }
}


文章来源: How to reflect an interfaced type at runtime