با سلام...من داخل یک برنامه با ارور use unassignd local variable مواجه شدم با تحقیق فهمیدم که علت ارور مقدار اولیه ندادنه...ولی دلیل علمی این ارور رو متوجه نمیشم که چرا اولیه ندیم ارور میگیره
Printable View
با سلام...من داخل یک برنامه با ارور use unassignd local variable مواجه شدم با تحقیق فهمیدم که علت ارور مقدار اولیه ندادنه...ولی دلیل علمی این ارور رو متوجه نمیشم که چرا اولیه ندیم ارور میگیره
با سلام
بدون کد چطور راهنمایی کنیم؟
کد برنامه بصورت زیره...دلیل ارور که توی اینترنت جستجو کردم مقدار اولیه ندادنه ولی نمیفهمم چرا وقتی مقدار اولیه نمیدیم خطا میگیره
private void button1_MouseDown(object sender, MouseEventArgs e)
{
string message;
if (e.Button == MouseButtons.Left)
message = "you clicked left button";
else if (e.Button == MouseButtons.Middle)
message = "you clicked middle button";
else if (e.Button == MouseButtons.Right)
message = "you clicked middle button";
message += "(" + e.X.ToString() + "," + e.Y.ToString() + ")";
MessageBox.Show(message);
}
بخاطر این هست که شما + گداشتید یعنی متن قبلی رو + متن جدید کن، خب قبلش چیزی وجود نداره که بخواد +جدید کنه
واسه این وضعیت شما دلیلش به این خاطره که کامپایلر انقد هوشمند نیست که بدونه شما داری روی ابجکت e و پراپرتی buttonش شرط if و else میذاری و نتیجه این شرط ها از سه حالت خارج نیست، در این حالت کامپایلر فرض رو بر بدترین حالت ممکن میذاره که هیچکدوم از سه شرط برقرار نباشن واسه همین متغیر message هیچ مقداری نمیگیره و وقتی به خط 10 میرسه قبلش هیچ مقداری توی message وجود نداره که عمل + رو روش انجام بده و این منطقی نیست پس بهتون ارور میده
اما برای راه حل شما میتونی خودت شرط هارو جوری تعریف کنی که از همین سه حالت خارج نباشه، میتونی به جای else if آخری، فقط بنویسی else و دیگه نیازی به قسمت if نخواهد بود:
توی این کدی که ویرایش کردم حتما یکی از شرط ها اجرا میشهstring message;
if (e.Button == MouseButtons.Left)
message = "you clicked left button";
else if (e.Button == MouseButtons.Middle)
message = "you clicked middle button";
else
message = "you clicked middle button";
message += "(" + e.X.ToString() + "," + e.Y.ToString() + ")";
MessageBox.Show(message);
ممنون...متوجه شدم بخاطر همون =+message هست چون هرچند در محیط اجرایی ابتدا مقدار داخل message قرار میگیره ولی کامپایلر زمان اجرا message رو بدون مقدار اولیه میبینه مشکل با یک else بجای else if اخر هم حل میشه
در زبان سی شارپ باید متغیر محلی توسط برنامه نویس مقداردهی اولیه شود.