为什么我不能在VB中投影ToString()? [英] Why can't I project ToString() in VB?

查看:108
本文介绍了为什么我不能在VB中投影ToString()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您尝试在Visual Basic .NET中编译以下查询,则它将失败.

If you try to compile the query below in Visual Basic .NET, it fails.

From x In {1, 2} Select x.ToString()

编译器给出的错误是:

范围变量名称不能与"Object"类的成员名称匹配.

Range variable name cannot match the name of a member of the 'Object' class.

等效的C#查询没有什么问题,

There is nothing wrong with the equivalent C# query, though:

from x in new[]{1, 2} select x.ToString()

对于采用格式(它是Int32的成员,而不是Object的成员)的ToString重载,不会发生这种情况.只要Object的其他成员不接受参数,它的确会发生:使用GetType和GetHashCode会失败.使用Equals(object)进行编译.

This does not happen with the ToString overload that takes a format (it is a member of Int32, not Object). It does happen with other members of Object, as long as they don't take an argument: with GetType and GetHashCode it fails; with Equals(object) it compiles.

为什么要设置此限制,我可以使用哪些替代方法?

Why is this restriction in place, and what alternatives can I use?

推荐答案

这就是我的理解方式.考虑以下代码:

Here's how I understand it. Consider the following code:

Dim q = From x In {"Bob", "Larry"}
        Select x.Length
        Select Length * 2

在上面的查询中,VB编译器基于表达式x.Length自动为您自动猜测Length变量的名称​​ .现在,您确实没有为此询问;无论您是否喜欢它,它都是所提供的功能.但现在考虑一下:

In the query above, the name of the Length variable is automatically "guessed" for you by the VB compiler based on the expression x.Length. Now, it's true that you didn't ask for this; it's just a feature that's provided whether you like it or not. But now consider this:

Dim q = From x In {"Bob", "Larry"}
        Select (x.Length)
        Select Length * 2

以上内容无法编译,因为第一个Select子句中的表达式不像第一种情况那样简单(信不信由你);括号使问题变得很复杂,编译器就不选择名称Length了;相反,它会生成一个无法从代码中使用的名称.

The above does not compile because the expression inside the first Select clause is not as simple as in the first case (believe it or not); the parentheses complicate matters just enough for the compiler not to pick the name Length; instead, it generates a name that is not usable from code.

所以ToString()基本上发生的是,此表达式足够简单,编译器可以使用它生成变量名,如果扩展查询以使用该变量名,则可以使用 变量,例如:

So basically what's happening with ToString() is that this expression is simple enough for the compiler to use to generate a variable name, which could be used if the query were expanded to make use of this variable, e.g.:

Dim q = From x In { 1, 2 }
        Select x.ToString()
        Select ToString.Length

但是,ToString不是变量的合法名称,因为它是System.Object的成员(为什么LINQ查询中的变量会是这种情况,而标准局部变量不是这种情况,我不能说)

However, ToString is not a legal name for a variable since it is a member of System.Object (why this would be the case for variables within LINQ queries but not for standard local variables, I couldn't say).

这篇关于为什么我不能在VB中投影ToString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆