Implicitly defined variable throws run-time error while explicitly defined does not

烈酒焚心 提交于 2019-12-02 03:25:25

问题


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

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

If I'm understanding this correctly, everything should work exactly the same. However, an error is thrown when calling 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.


回答1:


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

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

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.

Thus you can just declare it without the keyword New

Dim oSearchRoutines As SearchClient

Related question: VB.NET: impossible to use Extension method on System.Object instance



来源:https://stackoverflow.com/questions/47657062/implicitly-defined-variable-throws-run-time-error-while-explicitly-defined-does

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!