当我有一个按钮时,单击将标签的值更改为类对象的名称,我收到错误
“当前上下文中不存在'maxwell'这个名称”
有人能告诉我如何引用我创建的对象的数据成员吗?我希望我创建的狗可以在整个应用程序和我的应用程序中的所有按钮中访问。
这是我的代码:
public partial class MainWindow : Window
{
public class Dog
{
string name;
int length;
public Dog(string nm)
{
name = nm;
}
}
public MainWindow()
{
InitializeComponent();
Dog maxwell = new Dog("Maxwell");
Dog fred = new Dog("Fred");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
LabelName.Content = maxwell.name;
}
}
}
答案 0 :(得分:3)
您希望在班级maxwell
中将MainWindow
声明为field:
public partial class MainWindow : Window
{
public class Dog
{
string name;
int length;
public Dog(string nm)
{
name = nm;
}
}
private Dog maxwell;
private Dog fred;
public MainWindow()
{
InitializeComponent();
maxwell = new Dog("Maxwell");
fred = new Dog("Fred");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
LabelName.Content = maxwell.name;
}
}
答案 1 :(得分:0)
这是更先进的方法。 请注意,该类的方法只能访问类范围/主体
中声明的属性public partial class MainWindow : Window
{
// Inner Classes
public class Dog
{
private string name;
public string Name {
get{ return this.name };
set{ this.name = value}'
}
private int length;
public int Length {
get{ return this.length };
set{ this.length = value}'
}
public Dog( string _name )
{
this.name = _name;
}
}
// Properties
// For storing dogs
private Dicionary<string, Dog> Dogs;
// Methods
public MainWindow()
{
InitializeComponent();
// New dictionary of dogs
Dogs = new Dictionary<string, Dog>();
// adding Dogs objects
Dogs.add("maxwell", new Dog("Maxwell));
Dogs.add("fred", new Dog("Fred"));
}
private void Button_Click(object sender, RoutedEventArgs e)
{
LabelName.Content = Dogs["maxwell"].Name;
LabelLength.Content = Dogs["maxwell"].Length;
}
}