我正在try 创建一个在泛型ReadOnlySpan<T>
上操作的方法,这样我就可以在不更改代码的情况下传递数组或堆栈分配的缓冲区.我还希望将类型T
限制为仅为值类型.
该方法如下所示:
void Test1<T>(ReadOnlySpan<T> foo) where T : struct
{
}
但是,如果不传递类型参数,编译器就无法推断类型:
Test1(new[] {42}); // Doesn't compile
Test1<int>(new[] {42}); // Compiles
我也try 了不同的方法,我发现了一些有趣的行为:
void Test1<T>(ReadOnlySpan<T> foo) where T : struct
{
}
void Test2<T>(T[] foo) where T : struct
{
}
void Test3<T>(T[] foo)
{
}
void Test4<T>(ReadOnlySpan<T> foo)
{
}
void Test5<T>(List<T> foo) where T : struct
{
}
void Test6<T>(List<T> foo)
{
}
Test1(new[] {42}); // NO
Test2(new[] {42}); // OK
Test3(new[] {42}); // OK
Test4(new[] {42}); // NO
Test5(new List<int> {42}); // OK
Test6(new List<int> {42}); // OK
Test1<int>(new[] {42}); // OK
Test4<int>(new[] {42}); // OK
似乎类型推断不能仅对*Span
正常工作(数组和List
正常工作),我猜测ReadOnlySpan
是ref struct
的事实可能是问题的原因.
这种不同行为的真正原因是什么?
有没有一种方法可以帮助编译器推断ReadOnlySpan
in Test1()
方法的数据类型?
Update:个
我try 显式声明参数的类型:
ReadOnlySpan<int> testSpan = new[] {42};
Test1(testSpan); // OK!
Span<int> test = new[] {42};
Test1(test); // NO
看来这里真正的问题是隐式转换.
有谁能更好地解释一下吗?