我正在创建一个绘图应用程序,为此我需要为面板创建一个位图。我的问题是,当我得到桌面放置时,它给了我错误 “字段初始值设定项不能引用非静态字段,方法或属性'Form1.path'”
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Paint_AppLication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool mouse_down = false;
//My Problem
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
private Bitmap bit = new Bitmap(path + "\\" + "Bitmap.bmp");
// Other Code Not my problem
private Color col = Color.Black;
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
mouse_down = true;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
mouse_down = false;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
toolStripStatusLabel1.Text = e.X + ", " + e.Y;
if (mouse_down == true)
{
panel1.BackgroundImage = bit;
bit.SetPixel(e.X, e.Y, col);
}
}
private void button1_Click(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
col = colorDialog1.Color;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
答案 0 :(得分:0)
因为您的字段必须是静态的:
初始代码:
using System;
using System.Drawing;
internal class MyClass1
{
private readonly string _path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
private Bitmap _bitmap = new Bitmap(_path + "\\" + "Bitmap.bmp");
}
固定代码:
using System;
using System.IO;
internal class MyClass2
{
private static readonly string _path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
private Bitmap _bitmap = new Bitmap(_path + "\\" + "Bitmap.bmp");
}
更好的是,让System.IO.Path
类构建路径:
不再需要静态字段。
using System;
using System.Drawing;
using System.IO;
internal class MyClass3
{
private Bitmap _bitmap =
new Bitmap(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Bitmap.bmp"));
}