c# - .NET Core Cast 与实现接口的类型的泛型类型参数接口
问题描述
在 .NET Core C# 中,我正在尝试这样的事情:
(IInterface<IParameter>)instance
实例在哪里new Implementation<Parameter>()
和Implementation : IInterface
&Parameter : IParameter
问题在于泛型参数的转换。当我提供Parameter
而不是IParameter
它工作但在编译时没有办法知道IParameter
将使用哪种类型的实现。所有这些对象都将通过反射创建。
那么这个演员有什么办法吗?或者其他一些实现这一点的方法,比如不提供泛型类型参数,就像你可以使用typeof
.
编辑感谢 Ziriax
一个完整的工作示例:
interface IInterface
{
void Run(TInput input);
}
abstract class AbstractClass<TInput> : IInterface
where TInput : IParameter
{
public abstract void Execute(TInput input);
public void Run(IParameter input)
{
Execute((TInput)input);
}
}
interface IParameter {}
class Implementation : AbstractClass<Parameter>
{
public void Run(Parameter input)
{
}
}
class Parameter : IParameter {}
class Program
{
static void Main()
{
object instance = new Implementation();
var castInstance = (IInterface) instance;
castInstance.Run(new Parameter());
}
}
解决方案
正如你现在所拥有的,这是行不通的。你的Implementation
类 implements IInterface<Parameter>
,所以它的Run
方法只接受具体Parameter
类型的参数,而IInterface<IParameter>
要求它的Run
方法接受任何类型的实例 implements IParameter
。
如果允许您尝试执行的演员类型,我可以定义一个不同的类来实现IParameter
,例如:
public class DifferentParameter : IParameter { ... }
然后做:
castInstance.Run(new DifferentParameter());
但是你Implementation
的Run
方法不行DifferentParameter
!
因此,.NET 会阻止您执行转换本身。
在某些情况下允许这种类型的转换 - 如果您的接口被定义为:
interface IInterface<out TOutput>
where TOutput : IResult
{
TOutput Run();
}
通过使泛型参数out
,它使接口协变。这限制了类型参数的使用作为方法调用的结果,但是对于协变接口,像你这样的转换是允许的。
您可以在.NET 文档中找到大量关于协变和逆变的文档。
推荐阅读
- tensorflow - tensorflow_core._api.v2.random 没有属性 Generator
- node.js - 如果依赖项已经加载,Sinon 存根不会改变行为
- discord.js - 如何在没有命令召唤的情况下设置权限?
- python - Python3读取文件并将具有int值的二维数组放置一行
- reactjs - nextjs:_app.js 在包装组件之前渲染子组件(异步反应上下文依赖于索引数据库浏览器存储)
- python - Django Rest 框架:登录
- c# - ASP.NET Core 3.1 默认身份验证如何工作?
- python - Numpy 数组相等布尔值
- rxjs - 将项目升级到 Angular 8
- python - Plotly:如何为 plotly 直方图自定义不同的 bin 宽度?