Visual studio показывает несуществующие ошибки

I’m not sure if anyone else has encountered this but often, when I open this particular solution, I see a whole list of errors (see below).

Error Image

If I double click one of them, then Visual Studio seems to wake up and the errors relating to that particular cs file disappear. This isn’t a critical issue and is more on an irritation than anything else but I wonder, is there perhaps something wrong with my code that’s causing this false-positive or is it random Visual Studio behaviour?

asked May 18, 2017 at 10:30

Daniel's user avatar

4

I had this problem too.
Deleting bin and obj folders not work.
Cleaning solution not work.
Various platform I need to be as is.

Helped me close solution and delete folder .vs, which is often full of problematic mess. After opening solution all false errors disappeared.

answered Aug 16, 2019 at 6:30

bmi's user avatar

bmibmi

6622 gold badges10 silver badges17 bronze badges

3

As mentioned in a comment, you can do a Clean and Rebuild. If that does not work for you, you can browse to the solution folder and within each of the project folders delete the bin and obj folders. Then perform a build.

You may also want to look into your Configuration Manager and ensure that all of your projects are set to the same Configuration (Debug/Release) and Platform (Any CPU/x86/etc…) and marked to build for that configuration.

Finally, you may also want to check the Build Order for your solution. Ensure that projects are all built in the proper order.

— Edit:

On thing brought up in comments that I will add here was to make sure that any library projects in the solution are added as Project References rather than referencing the output DLL directly.

answered May 18, 2017 at 10:37

gmiley's user avatar

gmileygmiley

6,5311 gold badge13 silver badges25 bronze badges

8

Something that has only become evident in later years, and is only relevant upon reflection on this old question, is that the particular solution that we experience this issue in contains a Website project and NOT a WebApplication project. This became evident when we started to look deeper into these recurring errors and noted that they only ever related to codebehind files and all had to do with the Control Name not existing in the current context.

Amongst the various differences between the two project types, it seems that the lack of designer files for each ASP page may be a contributing factor. The error disappears as soon as you double click it potentially indicating that VS is not able to keep track of the control references until you open the relevant page / codebehind file.

We’re moving over to a Web Application as a temporary measure.

Hope this insight helps someone else!

answered Jul 29, 2020 at 11:43

Daniel's user avatar

DanielDaniel

2,1675 gold badges23 silver badges44 bronze badges

При компиляции кода в Vs 2019 выдает 2 ошибки, но красных подчеркиваний в коде нет.
В списке ошибок тоже пусто.
лог студии

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class MoveArea : MonoBehaviour, IPointerDownHandler, IDragHandler, IEndDragHandler
{
    public bool IsDrag;
    public void OnDrag(PointerEventData eventdata)
    {
        Debug.Log(1);
        Vector2 pos = transform.position - (new Vector3(eventdata.position.x, eventdata.position.y, 0)); //
        Vector2 direction = new Vector2(pos.x, pos.y + 10);//
        Debug.Log(direction);
        IsDrag = true;
    }
    public void OnEndDrag(PointerEventData eventdata)
    {
        Debug.Log(2);
        IsDrag = false;
    }
    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log(3);
    }
}

С++ Visual Studio 2022 Preview 5.0 показывает несуществующие ошибки

Visual Studio 2022 Preview 5.0 — это последняя предварительная версия популярной интегрированной среды разработки (IDE) от Microsoft для языка программирования C++. В этой версии было реализовано множество новых функций и улучшений, однако некоторые разработчики обнаружили, что IDE иногда показывает несуществующие ошибки.

Когда разработчик программирования на C++ с использованием Visual Studio, одним из наиболее важных аспектов является использование инструментов статического анализа, чтобы обнаружить потенциальные проблемы в коде, прежде чем программа будет скомпилирована и выполнена.

Один из таких инструментов — это компилятор Visual C++ в Visual Studio. Он отвечает за преобразование исходного кода на языке C++ в исполняемый код, который может быть запущен на машине пользователя. Компилятор может обрабатывать огромные объемы кода и выдавать сообщения об ошибках, предупреждениях и других проблемах, связанных с синтаксисом и семантикой.

Однако, некоторые разработчики, использующие Visual Studio 2022 Preview 5.0, заметили, что иногда компилятор выдает ошибки, которые не имеют реального основания. Эти ошибки могут привести к ненужным задержкам в разработке и лишним трудностям для программистов.

Например, представим, что у нас есть следующий простой фрагмент кода:

#include <iostream>
using namespace std;

int main() {
int x = 10;
cout << "Number: " << x << endl;

    return 0;
}

На первый взгляд, этот код выглядит корректно и не должен вызывать никаких ошибок. Однако, Visual Studio 2022 Preview 5.0 иногда будет выдавать следующую ошибку:

«error C2065: ‘cout’: undeclared identifier»

Ошибка указывает, что идентификатор «cout» не объявлен, что фактически неверно, поскольку он является частью стандартной библиотеки C++ и должен быть доступен в любом проекте на языке C++.

Подобные несуществующие ошибки вызывают недоумение и сбивают с толку разработчиков, особенно тех, кто только начинает изучать язык программирования C++ и использует Visual Studio в качестве своего основного инструмента разработки.

Однако, несмотря на то, что эти ошибки не являются реальными, они все равно отображаются в IDE и могут быть причиной замедления работы программиста. Разработчики могут тратить время на поиск решений в своих программах, даже не подозревая, что они сталкиваются с фантомными ошибками.

Тем не менее, стоит отметить, что эта проблема связана только с Visual Studio 2022 Preview 5.0, и предполагается, что она будет исправлена в финальной версии Visual Studio 2022. Команда разработчиков Microsoft уже осведомлена о проблеме и работает над ее устранением.

Временным решением для этой проблемы может быть использование предыдущих версий Visual Studio, которые лишены этой ошибки. Также, разработчики могут воспользоваться альтернативными IDE, такими как CLion или Qt Creator, чтобы избежать фантомных ошибок и продолжить разработку своих проектов без проблем.

В заключение, Visual Studio 2022 Preview 5.0, несмотря на множество новых возможностей и улучшений, иногда показывает несуществующие ошибки в языке программирования C++. Эти фантомные ошибки могут вызывать затруднения и замедлять процесс разработки. Однако, с учетом того, что это предварительная версия, данная проблема предполагается быть исправленной в будущих обновлениях Visual Studio 2022. Разработчики имеют возможность использовать предыдущие версии Visual Studio или другие IDE, чтобы избежать этих фантомных ошибок до выхода исправлений от Microsoft.

6193bf5b314e8962905291.png


  • Вопрос задан

  • 836 просмотров

Закрой приложение.
Удали сгенерируемые .sln файлы в папке с проектом. Открой приложение нажми в External tools -> regenerate project files.
Открой заново после всех манипуляций редактор.

В vsCode по типу такой была ошибка, но с пространством имён UI

Пригласить эксперта

Я вижу, что вы открываете VS не из юнити. Добавьте в настройках юнити в качестве редактора кода VS 2019. К сожалению я не помню путь к этой найтроке, погуглите.


  • Показать ещё
    Загружается…

21 сент. 2023, в 20:54

10000 руб./за проект

21 сент. 2023, в 20:40

20000 руб./за проект

21 сент. 2023, в 19:28

10000 руб./за проект

Минуточку внимания

Здесь коллекция популярных ответов. Upvote ОП ответа, если он помог вам:

Вариант 1. Очистка, сборка и обновление (опция @Mike Fuchs)

Как упомянул @Mike Fuchs, попробуйте следующие операции:

В меню «Построение»> «Чистое решение».

А также

В меню Build> Build Solution

и выберите проект, о котором идет речь, и нажмите кнопку обновления:

Изображение 106607

Вариант 2: очистить, закрыть, перезапустить и построить (опция @Pixel)

Как упоминалось @Pixel, попробуйте следующую последовательность операций:

  1. Чистый раствор
  2. Закрыть Visual Studio
  3. Откройте Visual Studio
  4. Построить решение

Вариант 3: очистить кеш ReSharper (опция @CydrickT)

Если у вас есть ReSharper, попробуйте очистить кеш ReSharper:

В меню ReSharper> Параметры> Среда> Общие> Очистить кэш

и отключение и повторное включение ReSharper:

В меню Инструменты> Параметры> ReSharper> Общие> Приостановить/Восстановить

Вариант 4. Удалите файл .suo (опция @Neolisk).

Как уже упоминалось @Neolisk, удаление файла .suo может решить вашу проблему. Для Visual Studio 2015 файл находится в:

[Путь решения]/. Vs/[Имя решения]/v14/.suo

И для Visual Studio 2017:

[Путь решения]/. Vs/[Имя решения]/v15/.suo

Обратите внимание, что каталог .vs скрыт.

Вариант 5: выгрузить и перезагрузить проект (опция @TTT)

Как упоминалось в @TTT, попробуйте выгрузить проект, который вызывает проблемы:

В обозревателе решений щелкните правой кнопкой мыши проект «Выгрузить проект».

И перезагрузить его

В обозревателе решений щелкните правой кнопкой мыши проект «Перезагрузить проект».

Вариант 6: удалить и добавить ссылку на Microsoft.CSharp (опция @Guilherme)

Как упомянул @Guilherme, попробуйте удалить и добавить ссылку на «Microsoft.CSharp» из проектов, в которых есть проблемы.

В обозревателе решений разверните проект, разверните «Ссылки», щелкните правой кнопкой мыши «Microsoft.CSharp» и выберите «Удалить».

Затем щелкните правой кнопкой мыши References> Add Reference, выберите «Microsoft.CSharp» из списка и нажмите «OK».

It’s always fun when Visual Studio (ie @drunkvs) can’t recite the alphabet backwards: The code below builds just fine when running through the compiler, but Visual Studio displays Intellisense errors in the Error Window and in the code with underlined squiggles:

The actual build of the code succeeds, but Intellisense is flagging several classes as missing even though they clearly exist and clearly compile properly.

IntelliSense is High!

So IntelliSense sometimes goes off the rails and if you see errors in your project that don’t make sense, first check to see if the errors are related to Intellisense.

Notice the drop down in the error list that lets you see Build + Intellisense which, in the case above produces 3 errors, but no errors if I just show Build Only:

Note the Intellisense error drop down is a new feature so you may not see it in older versions of Visual Studio. Not sure when it arrived but it was in one of the late VS 2015.x updates.

Clearing up Intellisense

There’s usually a simple solution when IntelliSense decides to sleep one off:

Delete the .vs folder

The .vs folder holds solution related temp data including the .suo file that caches intellisense and some debug data. That folder also holds Web site configuration data for Web projects and a few other things. It’s safe to delete this folder — Visual Studio recreates it when it’s missing.

Older versions of Visual Studio (prior to VS 2015) didn’t have a separate folder and dumped that same information into files in the solution’s root folder.

In these older versions you can fix Intellisense issues by deleting the Solution’s .suo file. Deleting the .vs folder in newer version nukes the .suo file which is responsible for cached IntelliSense and also some cached Debug data. When VS acts up and reports whacky errors that seem wrong, the burning down the .suo file is a nice quick thing to try first.

To do this:

  • Shut down VS
  • Nuke the .vs folder or the .suo file
  • Restart VS

The .suo file contains cached IntelliSense data and once that file is off, no amount of recompilation or clearing the project is going to help. Nuke the .suo file. or in VS 2015 or later the .vs folder and get back to sanity.

Compiler Errors?

I haven’t run into this problem very frequently but when it does happen it’s usually quite vexing resulting (for me at least) in a flurry of deleting output folders.

I have a standard set of steps I tend to go through when I get compiler errors that are wrong. Well, usually it’s me who’s wrong, not the compiler but on occasion I get to be right and the compiler is really wrong.

If you have errors that show under the Build Only dropdown, then the issue isn’t Intellisense.

This has gotten a lot better, but for a while invalid compiler errors were a big problem with the .NET SDK projects (.NET Core / .NET Standard) and in those cases the solution for me usually is (and still occasionally is):

  • Delete the obj folder completely
  • Delete the bin folder completely

While Visual Studio’s Clean project feature is supposed to address this, Clean will only clean up files the project knows about. If you’ve removed or renamed assemblies there may still be left over files in project output folders and deleting them cleans out the project completely.

This often fixes odd left over file issues that can cause strange compilation behavior. I never really considered Intellisense failure previously because Visual Studio didn’t differentiate compiler and IntelliSense Errors (or more accruately I didn’t notice the dropdown). I’d see errors in the Error list, yet my project would compile successfully, which was even more confusing.

Back to the Straight And Narrow

It’s nice that Visual Studio now explicitly shows these errors separately as Build and Intellisense errors, so you can take the sepearate actions to clean up this mess. In the past when the errors weren’t separated it was even more confusing with compiles succeeding, but the error list showing errors.

Now as to the cause of any of these errors? @drunkvs has some cleaning up to do after the barf fest of the previous night…

Понравилась статья? Поделить с друзьями:
  • Visual studio ошибка при создании проекта
  • Visual studio 2008 redistributable files возвратило ошибку vipnet
  • Visual studio ошибка при запуске приложения 0xc0000005
  • Visual studio installer произошла неизвестная ошибка
  • Vipnet выдает ошибку при установке