【问题标题】:How to change creating-ref-arguments inside class method?如何更改类方法中的创建引用参数?
【发布时间】:2011-07-19 11:35:42
【问题描述】:

指的是类变量的构造函数,可以在这个类期间分配工作。我如何在这个类中进行,我无法在构造函数中将它们分配给它们,而是在不同的方法中?

创建类:

 CreatePackWindow createPackWindow = new CreatePackWindow(ref title, ref description);
 if (createPackWindow.ShowDialog() == true)
 {
    Console.WiteLine(title, description);
 }

类 CreatePackWindow:

public partial class CreatePackWindow : Window
{
     public CreatePackWindow(ref string title, ref string description)
     {
         InitializeComponent();
     }

     private void btnCreate_Click(object sender, RoutedEventArgs e)
     {
            ???title = tbPackName.Text; **// How to assign here?**
            ???description = tbDescription.Text; **// How to assign here?**
            this.DialogResult = true;
            Close();
     }
     //..........
}

我知道您需要创建指向 titledescription 的指针以及使用它们的方法,但不知道该怎么做:(

请帮忙。 谢谢。

【问题讨论】:

    标签: c# .net wpf ref


    【解决方案1】:

    您不能使用ref 使字段 充当指针; ref 仅在通话期间有效。做你想做的事,也许:

    • 正确更新标题/描述(即 window.Title = "foo" 等)
    • 使用包装类作为中介 - 即两者都使用保持对类的引用带有标题/描述

    后者可能最接近你想要的。即有一个

    class Foo
    {
        public string Title{get;set;}
        public string Description{get;set;}
    }
    
    public partial class CreatePackWindow : Window
    {
         private readonly Foo foo;
         public CreatePackWindow(Foo foo)
         {
             InitializeComponent();
             this.Foo = foo;
         }
    
         private void btnCreate_Click(object sender, RoutedEventArgs e)
         {
                foo.Title = tbPackName.Text;
                foo.Description = tbDescription.Text;
                this.DialogResult = true;
                Close();
    
         }
    }
    

    var foo = new Foo();
    CreatePackWindow createPackWindow = new CreatePackWindow(foo);
     if (createPackWindow.ShowDialog() == true)
     {
        Console.WiteLine(foo.Title, foo.Description);
     }
    

    【讨论】:

      猜你喜欢
      • 2016-11-13
      • 1970-01-01
      • 2012-01-28
      • 2019-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      相关资源
      最近更新 更多