在How to reflect an interfaced type at runtime之后,我有一个我知道的从基类型DataPointProcessorBase继承的类型的实例,这个基类相对简单
public abstract class DataPointProcessorBase<T> : IDataPointProcessor<T> where T : class, IDataPointInput, new()
{
public abstract DataPointOutputBase GetOutput(T input);
}Age_Input实现该接口,并设置Age_Processor来接收该接口
public class Age_Input : DataPointInputBase, IDataPointInput
{
public int AgeExact { get; set; }
}
public class Age_Processor : DataPointProcessorBase<Age_Input>
{
...
}使用反射,我已经完成了正确转换它的一半,这样我就可以调用GetOutput()
你知道为什么我不能进入下面的第一个if语句吗?
var instance = Activator.CreateInstance(type);
if (instance is IDataPointProcessor<IDataPointInput>)//why can I not cast interface here?
{
//false
}
if (instance is IDataPointProcessor<Age_Input>)//hard-coded - works fine
{
var processor = instance as IDataPointProcessor<Age_Input>;
Age_Input temp = item as Age_Input;
if (temp is IDataPointInput)
{
//also true
}
var result = processor.GetOutput(temp);
}发布于 2018-06-01 05:52:24
据我所知,泛型类型在C#编译器中的工作方式是,在编译时在这些泛型参数中使用的强类型类型(意味着它们在代码中使用)是作为强类型类动态生成的(可能在MSIL层上)。
因此,在运行时,您的对象不具有具有泛型类型的继承类型,而是具有强类型的继承类型。
您可以为每个可能的强类型类型构建一个切换用例,并尝试对其进行强制转换。
https://stackoverflow.com/questions/50633096
复制相似问题