Dan*_*gen 13 c# visual-studio-2017
我刚刚升级到VS2017但是刚刚开始我的项目无法构建,因为我在使用VS15时遇到了一堆奇怪的编译器错误.
错误如:
Syntax Error; value expectedInvalid Expression Term '['Invalid Expression Term 'byte'Using the generic type requires 1 type argumentsusing System;
using System.Runtime.InteropServices;
namespace Error
{
class Program
{
static void Main()
{
Array array2D = null;
if (array2D is Bgra <byte>[,])
{
}
}
}
public interface IColor { }
public interface IColor<T> : IColor
where T : struct
{ }
public interface IColor2 : IColor { }
public interface IColor2<T> : IColor2, IColor<T>
where T : struct
{ }
public interface IColor3 : IColor { }
public interface IColor3<T> : IColor3, IColor<T>
where T : struct
{ }
public interface IColor4 : IColor { }
public interface IColor4<T> : IColor4, IColor<T>
where T : struct
{ }
[StructLayout(LayoutKind.Sequential)]
public struct Bgra<T> : IColor4<T>
where T : struct
{
public Bgra(T b, T g, T r, T a)
{
B = b;
G = g;
R = r;
A = a;
}
public T B;
public T G;
public T R;
public T A;
public override string ToString()
{
return $"B: {B}, G: {G}, R: {R}, A: {A}";
}
public const int IDX_B = 0;
public const int IDX_G = 1;
public const int IDX_R = 2;
public const int IDX_A = 3;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,完全相同的项目在VS15甚至VS13中编译正常.
根据我的测试,使用as运算符在 Visual Studio 2017 中按预期工作。
所以你可以使用
var tmp = array2D as Bgra<Byte>[,];
if (tmp != null) { ... }
Run Code Online (Sandbox Code Playgroud)
另外,is运算符确实适用于简单数组:
if (array2D is int[,]) { ... }
Run Code Online (Sandbox Code Playgroud)
也会编译。
所以当你有一个泛型数组时,这似乎是有问题的情况。事实上,如果你做类似的事情
if (array2D is List<int>[,]) { ... }
Run Code Online (Sandbox Code Playgroud)
你会得到编译错误。
下面的代码也会编译
object something = null;
if (something is List<int>) { ... }
Run Code Online (Sandbox Code Playgroud)
因此,唯一有问题的情况是使用泛型类型的数组作为运算符的参数时is。
作为旁注,我通常更喜欢使用as运算符来is运算符,因为通常您无论如何都需要目标类型中的变量。