首页 > 解决方案 > 有没有办法在 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但编译器不知道这一点并向我发送错误。首先,我想使用指针,但它们可以用于托管类型。

所以,这是我的问题:我如何告诉编译器我的对象具有正确的类型并且可以通过引用返回?

换句话说,如何将引用类型转换为另一种?

标签: c#.netpointers

解决方案


泛型并不意味着用于返回任何类型。泛型是类型安全的。因此,无论您使用 Get() 方法传递什么类型,您都需要准确返回该类型。

蝙蝠,您可以让所有类型从相同的接口或相同的基类型继承,然后返回该类型。

此外,需要考虑@RamblinRose 的评论


推荐阅读