如何声明构造函数?

编译程序时出现以下错误

“Microsoft.Samples.Kinect.ControlsBasics.SelectionDisplay’不包含带2个参数的构造函数”

我可能需要为我创建的新东西声明另一个构造函数,但我不知道该怎么做。 我在下面发布了相应的代码,你能帮我吗?

public SelectionDisplay(string itemId) { this.InitializeComponent(); this.messageTextBlock.Text = string.Format(CultureInfo.CurrentCulture,Properties.Resources.SelectedMessage,itemId); } var files = Directory.GetFiles(@".\GalleryImages"); foreach (var file in files) { FileInfo fileInfo = new FileInfo(file); BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.UriSource = new Uri(file, UriKind.Relative); bi.EndInit(); var button = new KinectTileButton { Label = System.IO.Path.GetFileNameWithoutExtension(file), Background = new ImageBrush(bi), Tag = file }; var selectionDisplay = new SelectionDisplay(button.Label as string, button.Tag as string); this.wrapPanel.Children.Add(button); } private void KinectTileButtonClick(object sender, RoutedEventArgs e) { var button = (KinectTileButton)e.Source; var image = button.CommandParameter as BitmapImage; var selectionDisplay = new SelectionDisplay(button.Label, button.Background); // aici poti apoi sa mai trimiti si imaginea ca parametru pentru constructor this.kinectRegionGrid.Children.Add(selectionDisplay); e.Handled = true; } 

http://sofzh.miximages.com/c%23/nno384.png

http://sofzh.miximages.com/c%23/33vm2k7.png

提前致谢!

编辑:现在我有一个不同的问题..我做了这些更改后得到三个新的错误。 通过所做的更改来查看新图像

http://sofzh.miximages.com/c%23/qwwqvn.png

好吧,你已经创建了一个带有一个参数的构造函数:

 public SelectionDisplay(string itemId) { //... } 

但是你传递了两个论点:

 new SelectionDisplay(button.Label as string, button.Tag as string); 

您可以向您拥有的构造函数添加参数,也可以创建一个新参数:

 public SelectionDisplay(string itemId, string someOtherValue) { //... } 

您应该创建SelectionDisplay的构造函数的重载或更改您已有的构造函数。 像这样:

 public SelectionDisplay(string itemId, string tag) { //Do something here } 

由于您使用两个参数创建SelectionDisplay的新实例,但其构造函数只接受一个参数。 ( string itemId ):

 //foreach new SelectionDisplay(button.Label as string, button.Tag as string); // //KinectTileButtonClick method new SelectionDisplay(button.Label, button.Background); 

你必须检查什么类型button.Labelbutton.Labelbutton.Background并创建一个具有这些值的新构造函数。

您可以在此处阅读有关Constructors更多信息

你有两行错误:

 var selectionDisplay = new SelectionDisplay(button.Label as string, button.Tag as string); 

 var selectionDisplay = new SelectionDisplay(button.Label, button.Background); 

并将构造函数定义为

 public SelectionDisplay(string itemId) { this.InitializeComponent(); this.messageTextBlock.Text = string.Format(CultureInfo.CurrentCulture,Properties.Resources.SelectedMessage,itemId); } 

如果你需要定义一些默认值,那么你需要这样做

 public SelectionDisplay(string itemId, string nextParam="default value") { this.InitializeComponent(); this.messageTextBlock.Text = string.Format(CultureInfo.CurrentCulture,Properties.Resources.SelectedMessage,itemId); } 

在这种情况下,您可以传递下一个参数或忽略它