c# - 有没有办法在 c# 中强制引用另一个 ref 类型?
问题描述
这是我的代码:
public ref TComponent Get<TComponent>()
where TComponent : struct, IComponent
{
for (int i = 0; i < Components.Length; i++)
{
if (Components[i] is TComponent)
{
// CS8151: The return expression must be of type 'T' because this method returns by reference
return ref Components[i];
}
}
// throw an exception
}
因此,如您所见,我试图返回对包含在 an 中的特定对象的引用,IComponent[]
并且我知道所有这些对象都是值类型。
如果我的方法返回 a 而不是,代码将编译ref IComponent
,但问题与我将被迫在方法的输出处进行转换相同。
我知道我要返回的对象具有正确的类型并且可以解释为 aTComponent
但编译器不知道这一点并向我发送错误。首先,我想使用指针,但它们可以用于托管类型。
所以,这是我的问题:我如何告诉编译器我的对象具有正确的类型并且可以通过引用返回?
换句话说,如何将引用类型转换为另一种?
解决方案
泛型并不意味着用于返回任何类型。泛型是类型安全的。因此,无论您使用 Get() 方法传递什么类型,您都需要准确返回该类型。
蝙蝠,您可以让所有类型从相同的接口或相同的基类型继承,然后返回该类型。
此外,需要考虑@RamblinRose 的评论
推荐阅读
- python - 如何在 Pytorch 中实现 dropout,以及在哪里应用它
- vhdl - VHDL 综合警告
- c - 如何将填充和换行符添加到 char 数组
- android - 如何在另一个项目中使用使用 dagger 2 构建的库项目?
- reactjs - 在运行反应应用程序的 Docker 容器中代理 API 请求
- javascript - 反应 | 可复用的下拉组件 | 如何获得选定的选项?
- docker - docker 中的 zeppelin-env.sh 文件在哪里?
- automaton - 如何在 Java 中实现这个自动机?
- google-apps-script - 从 Google App Script 设置 Google Drive 文件修改时间
- flutter - 隐藏顶部标题,直到滚动到特定高度