隐式定义的变量会引发运行时错误,而显式定义的变量不会 [英] Implicitly defined variable throws run-time error while explicitly defined does not

查看:108
本文介绍了隐式定义的变量会引发运行时错误,而显式定义的变量不会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用VB.NET遵循ReSharper的准则清理代码库。我目前有以下代码:

Using VB.NET, I'm trying to clean up a code base following ReSharper's guidelines. I currently have the following code:

'oSearchInput is defined outside this question
Dim oSearchRoutines As New SearchClient
Dim oSearchResults As List(Of SearchResult)

oSearchRoutines = 'WcfCallThatReturnsSearchClient

oSearchResults = oSearchRoutines.getSearchResults(oSearchInput).ToList

现在,此方法完全正常,但是ReSharper警告说作为新SearchClient 具有未分配值在任何执行路径中使用。因此,我删除了该部分以获取此代码:

Now this works completely fine, but ReSharper warns that As New SearchClient has 'Value assigned is not used in any execution path'. So I removed that part to get this code:

'oSearchInput is defined outside this question
Dim oSearchRoutines
Dim oSearchResults As List(Of SearchResult)

oSearchRoutines = 'WcfCallThatReturnsSearchClient

oSearchResults = oSearchRoutines.getSearchResults(oSearchInput).ToList

如果我正确地理解了这一点,那么一切应该都完全一样。但是,调用 ToList 时会引发错误:

If I'm understanding this correctly, everything should work exactly the same. However, an error is thrown when calling ToList:


公共成员 ToList

Public member 'ToList' on type 'SearchResult()' not found.

我不确定我为什么在这里的两个代码片段之间有什么区别。

I'm not exactly sure why there's any difference between the two snippets I have here.

推荐答案

因为您没有在自己的类型中使用 SearchClient 类型第二个示例, oSearchRoutines 将自动为 Object 类型。

Because you're not assinging the type SearchClient in your second example, oSearchRoutines will automatically be of type Object.

主要不允许类型为 Object 的表达式使用扩展方法,例如 ToList 方法。有关更多信息,请参见此处

An expression of type Object is mainly not allowed to use Extension methods, like for example the ToList-method. For further information see here

以下示例说明了此行为:

The following example illustrates this behaviour:

Dim x As Object
Dim y As String = "ABC"
x = y

Dim a As List(Of Char) = y.ToList() 'This will work
Dim b As List(Of Char) = x.ToList() 'This will throw a System.MissingMemberException






消息 分配的值未在任何执行路径中使用 ,因为在第一个示例中使用 New 重新声明 oSearchRoutines
这是不必要的,因为您正在向其添加新值...


The message Value assigned is not used in any execution path, appears because you're declaring oSearchRoutines with New in your first example. This is unnecessary because you're assinging a new value to it on the line...

oSearchRoutines = 'WcfCallThatReturnsSearchClient

...在任何地方使用之前。

...before using it anywhere.

因此,您只需声明它而无需使用关键字 New

Thus you can just declare it without the keyword New

Dim oSearchRoutines As SearchClient

相关问题:VB.NET:无法在System.Object实例上使用扩展方法

这篇关于隐式定义的变量会引发运行时错误,而显式定义的变量不会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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