Permalink
Cannot retrieve contributors at this time
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Compiler Error CS0103 |
Compiler Error CS0103 |
07/20/2015 |
CS0103 |
CS0103 |
fd1f2104-a945-4dba-8137-8ef869826062 |
Compiler Error CS0103
The name ‘identifier’ does not exist in the current context
An attempt was made to use a name that does not exist in the class, namespace, or scope. Check the spelling of the name and check your using directives and assembly references to make sure that the name that you are trying to use is available.
This error frequently occurs if you declare a variable in a loop or a try
or if
block and then attempt to access it from an enclosing code block or a separate code block, as shown in the following example:
[!NOTE]
This error may also be presented when missing thegreater than
symbol in the operator=>
in an expression lambda. For more information, see expression lambdas.
using System; class MyClass1 { public static void Main() { try { // The following declaration is only available inside the try block. var conn = new MyClass1(); } catch (Exception e) { // The following expression causes error CS0103, because variable // conn only exists in the try block. if (conn != null) Console.WriteLine("{0}", e); } } }
The following example resolves the error:
using System; class MyClass2 { public static void Main() { // To resolve the error in the example, the first step is to // move the declaration of conn out of the try block. The following // declaration is available throughout the Main method. MyClass2 conn = null; try { // Inside the try block, use the conn variable that you declared // previously. conn = new MyClass2(); } catch (Exception e) { // The following expression no longer causes an error, because // the declaration of conn is in scope. if (conn != null) Console.WriteLine("{0}", e); } } }
When my view loads, I need to check which domain the user is visiting, and based on the result, reference a different stylesheet and image source for the logo that appears on the page.
This is my code:
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
string imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
string imgsrc="/content/images/uploaded/store2_logo.gif";
}
}
Then, a little further down I call the imgsrc variable like this:
<a href="@Url.RouteUrl("HomePage")" class="logo"><img alt="" src="@imgsrc"></a>
I get an error saying:
error CS0103: The name ‘imgsrc’ does not exist in the current context
I suppose this is because the «imgsrc» variable is defined in a code block which is now closed…?
What is the proper way to reference this variable further down the page?
asked Sep 26, 2014 at 20:23
Simply move the declaration outside of the if block.
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="";
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store2_logo.gif";
}
}
<a href="@Url.RouteUrl("HomePage")" class="logo"><img alt="" src="@imgsrc"></a>
You could make it a bit cleaner.
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="/content/images/uploaded/store2_logo.gif";
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
}
}
answered Sep 26, 2014 at 20:26
masonmason
31.1k10 gold badges76 silver badges120 bronze badges
0
using System;
using System.Collections.Generic; (помогите пожалуйста та же самая
using System.Linq; ошибка PlayerScript.health =
using System.Text; 999999; вот на этот скрипт)
using System.Threading.Tasks;
using UnityEngine;
namespace OneHack
{
public class One
{
public Rect RT_MainMenu = new Rect(0f, 100f, 120f, 100f); //Rect это месторасположение меню по x,y и высота, ширина.
public int ID_RTMainMenu = 1;
private bool MainMenu = true;
private void Menu_MainMenu(int id) //Главное меню
{
if (GUILayout.Button("Название вашей кнопки", new GUILayoutOption[0]))
{
if (GUILayout.Button("Бессмертие", new GUILayoutOption[0]))
{
PlayerScript.health = 999999;//При нажатии на кнопку у игрока устанавливается здоровье 999999 //Здесь код, который будет происходить при нажатии на эту кнопку
}
}
}
private void OnGUI()
{
if (this.MainMenu)
{
this.RT_MainMenu = GUILayout.Window(this.ID_RTMainMenu, this.RT_MainMenu, new GUI.WindowFunction(this.Menu_MainMenu), "MainMenu", new GUILayoutOption[0]);
}
}
private void Update() //Постоянно обновляемый метод, все что здесь будет написанно будет создаваться бесконечно
{
if (Input.GetKeyDown(KeyCode.Insert)) //Кнопка на которую будет открываться и закрываться меню, можно поставить другую
{
this.MainMenu = !this.MainMenu;
}
}
}
}
Suraj Rao
29.3k11 gold badges96 silver badges103 bronze badges
answered Aug 31, 2020 at 9:26
4
C# Compiler Error
CS0103 – The name ‘identifier’ does not exist in the current context
Reason for the Error
You will usually receive this error when you are trying to use a identifier name in C# that doesnot exist with-in the current scope. One of the simple example of this error is when you declare a variable with-in a try block and try to access it in the catch block.
In the below example, the variable i is declared inside the try block, so its scope is restricted to the try block. When you try accessing it in the catch block is when you will receive the error.
using System; public class DeveloperPublish { public static void Main() { try { int i = 1; int j = 0; int result = i / j; } catch(DivideByZeroException) { string message = i + " is divivided by zero"; Console.WriteLine(message); } } }
Error CS0103 The name ‘i’ does not exist in the current context ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 16 Active
Solution
To fix the error move the declaration of the identifier that is causing the error to a higher scope so that it is available when it is accessed.
For example, to fix the error in the above code snippet, we just need to move the declaration of the identifier outside of the try block.
using System; public class DeveloperPublish { public static void Main() { int i = 1; try { int j = 0; int result = i / j; } catch(DivideByZeroException) { string message = i + " is divivided by zero"; Console.WriteLine(message); } } }
- Remove From My Forums
-
Question
-
User397255882 posted
My asp.net page runs fine in VWD Express 2010 but on the server i get this error:
error CS0103: The name 'DropDownList_Nodes' does not exist in the current context
If anyone can help me I would appreciate it.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; namespace OrionNodeEvent { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack)//only do on 1st page load { FillListBox(); } }//end Page_Load protected void Submit_Click(object sender, EventArgs e) { string connectionString = @"data source=****;initial catalog=****;user id=*****;" + "password=****;packet size=4096;persist security info=False;connect timeout=30000; Trusted_Connection=yes"; string insertSQL; DateTime currentTime = DateTime.UtcNow; insertSQL = @"USE **** INSERT INTO ***** ("; insertSQL += "Node_Name, Event, Solution, Time) "; insertSQL += "VALUES ('"; insertSQL += DropDownList_Nodes.SelectedItem.ToString() + "', '"; insertSQL += TextBox_Event.Text + "', '"; insertSQL += TextBox_Solution.Text + "', '"; insertSQL += currentTime + "')"; SqlConnection sql_connection = new SqlConnection(connectionString); SqlCommand sql_command = new SqlCommand(insertSQL, sql_connection); int added = 0;//counter for rows inserted to DB try { sql_connection.Open(); added = sql_command.ExecuteNonQuery(); Label_Info.Text = added.ToString() + " records inserted."; } catch(Exception error) { Label_Info.Text = error.Message; } finally { sql_connection.Close(); sql_connection.Dispose(); } }//end Submit_Click protected void FillListBox() { string connectionString = @"data source=****;initial catalog=****;user id=****;" + "password=****;packet size=4096;persist security info=False;connect timeout=30000; Trusted_Connection=yes"; DropDownList_Nodes.Items.Clear(); string selectSQL = @"USE **** SELECT ***, *** FROM *** ORDER BY ***"; SqlConnection sql_connection = new SqlConnection(connectionString); SqlCommand sql_command = new SqlCommand(selectSQL, sql_connection); SqlDataReader sql_reader; try { sql_connection.Open(); sql_reader = sql_command.ExecuteReader(); while (sql_reader.Read()) { ListItem newitem = new ListItem(); newitem.Text = sql_reader["****"].ToString(); newitem.Value = sql_reader["****"].ToString(); DropDownList_Nodes.Items.Add(newitem); }//end while sql_reader.Close(); sql_reader.Dispose(); }//end try catch(Exception error) { Label_Info.Text = error.Message; } finally { sql_connection.Close(); sql_connection.Dispose(); } }//end FillListBox public override void VerifyRenderingInServerForm(Control control) { return; } }//end public partial class _Default : System.Web.UI.Page }//end namespace OrionNodeEvent
// ASP PAGE *************************************** <%@ Language="C#" AutoEventWireup="true" CodeBehind="OrionNodeEvent.aspx.cs" Inherits="OrionNodeEvent._Default" Src="OrionNodeEvent.aspx.cs" %> <html> <head> <title>Orionz</title> </head> <body> <h2>Select a Node to add an event and resolution.</h2> <p><asp:DropDownList ID="DropDownList_Nodes" runat="server"></asp:DropDownList></p> <p><strong>Event</strong><asp:TextBox ID="TextBox_Event" runat="server" style="margin-left: 25px" Width="500px" Height="150px" TextMode="MultiLine" MaxLength="8000"></asp:TextBox></p> <p><strong>Solution</strong><asp:TextBox ID="TextBox_Solution" runat="server" style="margin-left: 10px" Width="500px" Height="150px" TextMode="MultiLine" MaxLength="8000"></asp:TextBox> </p> <p><asp:Button ID="Button_Submit" runat="server" Text="Submit" OnClick="Submit_Click"/></p> <p><asp:Label ID="Label_Info" runat="server" Text="" ></asp:Label> </p> </body> </html>
Answers
-
User397255882 posted
SOLVED:
Added these control statements to the Default.aspx.cs:
protected global::System.Web.UI.HtmlControls.HtmlForm form1; protected System.Web.UI.WebControls.Label Label_Info; protected System.Web.UI.WebControls.DropDownList DropDownList_Nodes; protected System.Web.UI.WebControls.TextBox TextBox_Event; protected System.Web.UI.WebControls.TextBox TextBox_Solution; protected System.Web.UI.WebControls.Button Button_Submit;
The server was ignoring the designer file.
Now it loads!
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
0 / 0 / 0
Регистрация: 03.03.2019
Сообщений: 7
1
03.03.2019, 22:27. Показов 13926. Ответов 11
Всем привет, перечитал много тем по поводу данной ошибки, но у меня немного другая ситуация, код компилируется нормально, без ошибок, но при запуске сервера выдает уже ошибки
Например у меня есть класс где функции транспорта, когда при запуске сервера я вызываю загрузку транспорта — выходит ошибка
Код
CS0103: The name 'VehicleF' does not exist in the current context -> Class1.cs:16
Файл запуска сервера
C# | ||
|
Файл с функциями транспорта
C# | ||
|
А так же где у меня идет работа с базой данных выходит ошибка
Код
CS0012: The type 'DbConnection' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. -> connect.cs:15
Добавлено через 1 час 24 минуты
Большое спасибо вам, но я перехожу по вашим ссылкам, там такие же ответы на другие ссылки, а затем опять ответы со ссылками, где-то на 5 переходе я бросил это занятие, так как видимо ответов здесь не бывает -_-
Добавлено через 9 минут
Тем более меня не интересуют темы где люди не обьявляют переменные, меня интересует почему у меня методы из одного класса не вызываются в другом, классы по разным файлам
Добавлено через 16 минут
Если я прописываю два класса в одном файле то все хорошо, а если по разным то вот такие ошибки, может кто сказать как линкануть файл? Указать его вначале? Подключить? Я думал что если все одним проектом то таких проблем быть не должно, но видимо ошибся
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
public static class MeshGenerator
{
public static MeshData GenerateTerrainMesh(float[,] borderedSizeMap, float borderedSizeMultiplier, AnimationCurve _borderedSizeCurve, int levelOfDetail)
{
AnimationCurve borderedSizeCurve = new AnimationCurve(_borderedSizeCurve.keys);
int borderedSize = borderedSizeMap.GetLength(0);
int meshSize = borderedSize - 2;
float topLeftX = (meshSize - 1) / -2f;
float topLeftZ = (meshSize - 1) / 2f;
int meshSimplificationIncrement = (levelOfDetail == 0) ? 1 : levelOfDetail * 2;
int verticesPerLine = (meshSize - 1) / meshSimplificationIncrement + 1;
MeshData meshData = new MeshData(verticesPerLine);
int[,] vertexIndicesMap = new int[borderedSize, borderedSize];
int meshVertexIndex = 0;
int borderVertexIndex = -1;
for (int y = 0; y < borderedSize; y += meshSimplificationIncrement)
{
for (int x = 0; x < borderedSize; x += meshSimplificationIncrement)
{
bool isBorderVertex = y == 0 || y == borderedSize - 1 || x == 0 || x == borderedSize - 1;
if (isBorderVertex)
{
vertexIndicesMap[x, y] = borderVertexIndex;
borderVertexIndex--;
}
else
{
vertexIndicesMap[x, y] = meshVertexIndex;
meshVertexIndex++;
}
}
}
for (int y = 0; y < borderedSize; y+= meshSimplificationIncrement)
{
for (int x = 0; x < borderedSize; x+= meshSimplificationIncrement)
{
int vertexIndex = vertexIndicesMap[x, y];
Vector2 percent = new Vector2((x - meshSimplificationIncrement) / (float)meshSize, (y - meshSimplificationIncrement) / (float)meshSize);
float height = heightCurve.Evaluate(heightMap[x, y]) * heightMultiplier;
Vector3 vertexPosition = new Vector3(topLeftX + percent.x * meshSize, height, topLeftZ - percent.y * meshSize);
meshData.AddVertex(vertexPosition, percent, vertexIndex);
if (x < borderedSize - 1 && y < borderedSize - 1)
{
int a = vertexIndicesMap[x, y];
int b = vertexIndicesMap[x + meshSimplificationIncrement, y];
int c = vertexIndicesMap[x, y + meshSimplificationIncrement];
int d = vertexIndicesMap[x + meshSimplificationIncrement, y + meshSimplificationIncrement];
meshData.AddTriangle(a, d, c);
meshData.AddTriangle(d, a, b);
}
vertexIndex++;
}
}
return meshData;
}
}
public class MeshData
{
Vector3[] vertices;
int[] triangles;
Vector2[] uvs;
Vector3[] borderVertices;
int[] borderTriangles;
int triangleIndex;
int borderTriangleIndex;
public MeshData(int verticesPerLine)
{
vertices = new Vector3[verticesPerLine * verticesPerLine];
uvs = new Vector2[verticesPerLine * verticesPerLine];
triangles = new int[(verticesPerLine - 1) * (verticesPerLine - 1) * 6];
borderVertices = new Vector3[verticesPerLine * 4 + 4];
borderTriangles = new int[24 * verticesPerLine];
}
public void AddVertex(Vector3 vertexPosition, Vector2 uv, int vertexIndex)
{
if (vertexIndex < 0)
{
borderVertices[-vertexIndex - 1] = vertexPosition;
}
else
{
vertices[vertexIndex] = vertexPosition;
uvs[vertexIndex] = uv;
}
}
public void AddTriangle(int a, int b, int c)
{
if (a < 0 || b < 0 || c < 0)
{
borderTriangles[borderTriangleIndex] = a;
borderTriangles[borderTriangleIndex + 1] = b;
borderTriangles[borderTriangleIndex + 2] = c;
borderTriangleIndex += 3;
}
else
{
triangles[triangleIndex] = a;
triangles[triangleIndex + 1] = b;
triangles[triangleIndex + 2] = c;
triangleIndex += 3;
}
}
Vector3[] CalculateNormals()
{
Vector3[] vertexNormals = new Vector3[vertices.Length];
int triangleCount = triangles.Length / 3;
for (int i = 0; i < triangleCount; i++)
{
int normalTriangleIndex = i * 3;
int vertexIndexA = triangles[normalTriangleIndex];
int vertexIndexB = triangles[normalTriangleIndex + 1];
int vertexIndexC = triangles[normalTriangleIndex + 2];
Vector3 triangleNormal = SurfaceNormalFromIndices(vertexIndexA, vertexIndexB, vertexIndexC);
vertexNormals[vertexIndexA] += triangleNormal;
vertexNormals[vertexIndexB] += triangleNormal;
vertexNormals[vertexIndexC] += triangleNormal;
}
int borderTriangleCount = borderTriangles.Length / 3;
for (int i = 0; i < triangleCount; i++)
{
int normalTriangleIndex = i * 3;
int vertexIndexA = borderTriangles[normalTriangleIndex];
int vertexIndexB = borderTriangles[normalTriangleIndex + 1];
int vertexIndexC = borderTriangles[normalTriangleIndex + 2];
Vector3 triangleNormal = SurfaceNormalFromIndices(vertexIndexA, vertexIndexB, vertexIndexC);
if (vertexIndexA >= 0)
{
vertexNormals[vertexIndexA] += triangleNormal;
}
if (vertexIndexB >= 0)
{
vertexNormals[vertexIndexB] += triangleNormal;
}
if (vertexIndexC >= 0)
{
vertexNormals[vertexIndexC] += triangleNormal;
}
}
for (int i = 0; i < vertexNormals.Length; i++)
{
vertexNormals[i].Normalize();
}
return vertexNormals;
}
Vector3 SurfaceNormalFromIndices(int indexA, int indexB, int indexC)
{
Vector3 pointA = (indexA < 0) ? borderVertices[-indexA - 1] : vertices[indexA];
Vector3 pointB = (indexB < 0) ? borderVertices[-indexB - 1] : vertices[indexB];
Vector3 pointC = (indexC < 0) ? borderVertices[-indexC - 1] : vertices[indexC];
Vector3 sideAB = pointB - pointA;
Vector3 sideAC = pointC - pointA;
return Vector3.Cross(sideAB, sideAC).normalized;
}
public Mesh CreateMesh()
{
Mesh mesh = new Mesh();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uvs;
mesh.normals = CalculateNormals();
return mesh;
}
}
Скрипт не работает
Скрипт не работает
Вот такой простенький скрипт но консоль выдает данную ошибку=Assets/M2.cs(8,20): error CS0103: The name `col’ does not exist in the current context
И еще желтую ошибку=Assets/M2.cs(10,28): warning CS0219: The variable `rotationY’ is assigned but its value is never used
Используется csharp
using System.Collections;
public class Moving2 : MonoBehaviour {
void Update ()
{
if(col.gameObject.name == «RollerBall»)
{
Quaternion rotationY = Quaternion.AngleAxis (180, Vector3.up);
}
}
}
- developers
- UNец
- Сообщения: 15
- Зарегистрирован: 30 янв 2016, 22:55
Re: Скрипт не работает
Smouk 03 мар 2016, 10:36
1. Из этого не понять в чем именно ошибка. Где объявлено col и зачем? Для получения имени объекта если скрипт висит на нем это не нужно.
В принципе не очень верно каждый update без необходимости сравнивать текст. Лучше при создании объекта использовать флаг или int с типом объекта, например.
2. Если перевести там прямо написано, что переменная rotationY никогда не используется.
Последний раз редактировалось Smouk 03 мар 2016, 10:39, всего редактировалось 2 раз(а).
- Smouk
- UNIт
- Сообщения: 146
- Зарегистрирован: 16 сен 2009, 08:47
Re: Скрипт не работает
BladeBloodShot 03 мар 2016, 10:38
Ну так переведи ошибки, нет определения col то бишь надо public var col = там чему то;
- BladeBloodShot
- UNец
- Сообщения: 38
- Зарегистрирован: 03 фев 2016, 22:31
Re: Скрипт не работает
developers 03 мар 2016, 12:06
А насчет 2 причины
- developers
- UNец
- Сообщения: 15
- Зарегистрирован: 30 янв 2016, 22:55
Re: Скрипт не работает
iLLoren 03 мар 2016, 13:59
developers писал(а):А насчет 2 причины
Научись разбираться с мелочами самостоятельно, тебе самому то не стыдно что имея видео о том как с 0 сделать всё правильно ты косячишь и вместо пересмотров урока ты плачешь на форуме о проблемах которые сам можешь легко решить?
-
iLLoren - UNIт
- Сообщения: 103
- Зарегистрирован: 31 дек 2015, 12:00
Re: Скрипт не работает
Tolking 03 мар 2016, 14:16
Желтая ошибка называется предупреждением и в переводе с английского гласит: ты нахрена опредилил переменную `rotationY’ если нигде ее не используешь!
Таки да!!! Английский знать надо или пользоваться переводчиком…
Ковчег построил любитель, профессионалы построили Титаник.
-
Tolking - Адепт
- Сообщения: 2684
- Зарегистрирован: 08 июн 2009, 18:22
- Откуда: Тула
Вернуться в Скрипты
Кто сейчас на конференции
Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 6