如果我有以下代码:
private void Check(bool a, bool b)
{
}
private void Check(int a, int b, int c, bool flag)
{
Check(a < b, a > (flag ? c : b - 10));
}
我在调用 Check(int, int)
时遇到编译时错误:
error CS0307: The variable 'int' cannot be used with type arguments
我也遇到了这些错误:
error CS0118: 'b' is a variable but is used like a type
error CS0118: 'a' is a variable but is used like a type
为什么会出现这些错误?代码有什么问题?
最佳答案
今天对我来说是美好的一天。我从没想过我会在野外看到其中一个!我只在编译器测试用例中见过这种情况。
考虑以下程序片段:
F(G<A,B>(7));
在 C# 1.0 中,这意味着“使用两个参数调用方法 F:G<A
和 B>(7)
。
但是 C# 2.0 添加了泛型。在 C# 2.0 中,这意味着“使用一个参数调用方法 F。该参数是对泛型方法 G<A, B>
的调用,使用一个参数 7”。
这是一个突破性的变化。 C# 有一些启发式方法来尝试确保匹配此模式的旧程序继续工作,但并非所有程序都能正常工作。
C# 正在解释你的程序
Check(a < b, a > (flag ? c : b - 10));
作为对 Check
的调用使用一个参数:调用泛型方法 a<b, a>
有一个参数。
正如您发现的那样,适合您的解决方案很简单:只需放入更多括号来分隔要检查的参数。
如果您有兴趣了解 C# 用来判断何时是泛型和何时不是泛型的确切规则,它是:
If a sequence of tokens can be parsed as a simple-name, member-access, or pointer-member-access ending with a type-argument-list, the token immediately following the closing > token is examined. If it is one of
( ) ] } : ; , . ? == != | ^
then the type-argument-list is retained as part of the simple-name, member-access or pointer-member-access and any other possible parse of the sequence of tokens is discarded. Otherwise, the type-argument-list is not considered to be part of the simple-name, member-access or pointer-member-access, even if there is no other possible parse of the sequence of tokens. Note that these rules are not applied when parsing a type-argument-list in a namespace-or-type-name.
相信我,必须实现这样的规则使得 C# 解析起来有点棘手。
关于c# - 编译器错误 : "error CS0307: The variable ' int' cannot be used with type arguments",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39669720/