简体   繁体   中英

Visual Studio Find all references ignores var

I want to find all references to some class in visual studio but instances defined with var are ignored.

Is there some way to fix this?

Here i am using SHIFT+F12 to get references

Shift+F12

The results are:

在此处输入图片说明

But when using ReportWindow on line 1197: 在此处输入图片说明

I get what i want

在此处输入图片说明

At this point in time, VS 2015, 2017 and 2019 have this behaviour for the built-in Find All References search, as well as Resharper's Find Usages and Find Usages Advanced search options. It is also expected behaviour.

The only time a var reference will be returned in the search results is when you make an explicit call to a constructor. Also, when a method is called and returned to variable that has been explicitly declared as the given type, that line will also be returned in the search results.

Personally, I like to use var only when it is obvious what is being returned and assigned to a variable, which is usually only when a constructor is called directly. This is also handy when declaring a class with a long and inconvenient name, avoiding having to type that type twice:

Dictionary<string, Ninja> trainees = new Dictionary<string, Ninja>();

Here is an example of a small program demonstrating where Find All References will find results and where it will not.

using System;
​
namespace VarSearchTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var ninja = NinjaAcademy.Train();     // <---------- does not find (implicit)
            Ninja ninja2 = NinjaAcademy.Train();  // <---------- finds (explicit type declaration)
            var chrisFarley = new Ninja();        // <---------- finds (explicit constructor call)


            Console.WriteLine(ninja.Hide());
            Console.WriteLine(ninja2.Hide());
            Console.WriteLine(chrisFarley.Hide());
        }
    }
​
    public class Ninja  // <-------------------- Find all references/usages
    {
        public string Hide()
        {
            return "Puff of smoke...";
        }
    }
​
    public static class NinjaAcademy
    {
        public static Ninja Train()  // <---------------- finds (explicit return type)
        {
            return new Ninja();      // <------------------ finds (explicit constructor call)
        }
    }
}

You can also track this github issue in case it ever changes in the future, as it would be handy to have implicit references easy to find. In the meantime, consider using var only in the scenarios where it provides convenience in the explicit situations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM