wpf 从另一个类访问非静态方法而无需实例化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17465713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:08:39  来源:igfitidea点击:

accessing non-static method from another class without instantiate

c#wpfvisual-studio-2010class

提问by Naresh

Title is my question. I will explain below.

标题是我的问题。我将在下面解释。

I am working on wpf application is vs2010. I have two windows, one is my MainWindow and another is a fileList window. In my fileList window, I have a list of files, which on click, should load the file. The onClick method is implemented in fileList class. The function to load the file is implemented in MainWindow partial class.

我正在研究 wpf 应用程序是 vs2010。我有两个窗口,一个是我的 MainWindow,另一个是 fileList 窗口。在我的 fileList 窗口中,我有一个文件列表,点击后应该加载文件。onClick 方法在 fileList 类中实现。加载文件的功能在 MainWindow 部分类中实现。

My fileList class in instantiated in MainWindow class to show the window. I cant instantiate MainWidow again. The function(method) in MainWindow can't be declared static because it uses other parameter which I can't (don't know how to) declared static.

我的 fileList 类在 MainWindow 类中实例化以显示窗口。我无法再次实例化 MainWidow。MainWindow 中的函数(方法)不能声明为静态,因为它使用了我不能(不知道如何)声明为静态的其他参数。

I am pasting relevant code below. Kindly help.

我在下面粘贴相关代码。请帮忙。

namespace test
{
  public partial class MainWindow : Window
     fileList fl = new fileList;

     public MainWindow()
     {
      InitializeComponent();
      fl.show();
      }

      public void porcessfile(string path)
      {
       //this method processes the the file at "path". It uses combobox and scrollviewer 
       //declared in xaml. I dont know how to declare static in xaml, else I will declare       
       //them static and change the whole method to static, so I can call it without  
       //instantiating. I tried making a nested-class, but then I can't  access variable 
       //declared in MainWindow (parent) class. Or there is a way to do that?

      }
}

and the other class:

和另一个类:

namespace test
{
  public partial class fileList : Window
  {
     public fileList()
     {
        IntializeComponent();
     }



     private void Button_click(object sender, RoutedEventsArgs e)
     {
      //code that gets "path" on click, works fine.

      processfile(string path); // what and how to do here.
     }
  }

} 

I sincerely hope I am clear. Please ask details if required.

我真诚地希望我清楚。如有需要请询问详情。

回答by Christian Sauer

Well, the easiest solution would be to simply give your Filelist window a constructor which accepts an delegate which points to your processfile method in the Mainwindows. Look at this article: http://www.codeproject.com/Articles/109000/C-Delegates-Step-by-Step

好吧,最简单的解决方案是简单地为您的 Filelist 窗口提供一个构造函数,该构造函数接受一个委托,该委托指向 Mainwindows 中的 processfile 方法。看这篇文章:http: //www.codeproject.com/Articles/109000/C-Delegates-Step-by-Step

Making it statis is not the solution -it would be a very ugly hack, which causes more trouble than the delegate.

让它 statis 不是解决方案 - 这将是一个非常丑陋的 hack,这会比委托造成更多的麻烦。

回答by Rafal

There is a static convenience access property for all windows in your application:

应用程序中的所有窗口都有一个静态的便捷访问属性:

Application.Current.Windows

应用程序.当前.Windows

Then simply take the first one (or figure out the right one if you have more then one) and cast to your MainWindowtype. And now you have an instance to call your method.

然后简单地选择第一个(或者如果你有更多则找出正确的)并转换为你的MainWindow类型。现在你有一个实例来调用你的方法。

回答by Avram Tudor

Ok, this should be fairly easy. You just need to declare an event in your FileList class which fires in your Button_click method sending the file path and subscribe to it from MainWindow, and call your processfile method with the argument you've just received.

好的,这应该很容易。您只需要在 FileList 类中声明一个事件,该事件在您的 Button_click 方法中触发,发送文件路径并从 MainWindow 订阅它,并使用您刚刚收到的参数调用您的 processfile 方法。

In your FileList class:

在您的 FileList 类中:

    public event EventHandler<EventArgs<string>> PathReceived = delegate { };

Publish this in your Button_click.

将此发布到您的 Button_click 中。

In your MainWindow class on cosntructor:

在构造函数上的 MainWindow 类中:

   this.fileList.PathReceived = (o,args) => this.ProcessFile(args.Value);

Publish code:

发布代码:

   this.PathReceived(null, new EventArgs<string>(yourPath));

EDIT:I forgot to provide you with the EventArgs class (it's from an old project of mine).

编辑:我忘了给你提供 EventArgs 类(它来自我的一个旧项目)。

public class EventArgs<T> : EventArgs
{
    /// <summary>
    /// Initializes a new instance of the <see cref="EventArgs{T}"/> class.
    /// </summary>
    /// <param name="value">The value.</param>
    public EventArgs(T value)
    {
        Value = value;
    }

    /// <summary>
    /// Gets the value.
    /// </summary>
    /// <value>
    /// The value.
    /// </value>
    public T Value { get; private set; }
}

回答by ashes999

Although it's something of an anti-pattern (because it resembles global variables and persists state, which makes testing more difficult), you can use the singleton pattern here:

尽管它是一种反模式(因为它类似于全局变量并保持状态,这使得测试更加困难),但您可以在此处使用单例模式:

public partial class MainWindow {
  private static MainWindow instance = new MainWindow();

  public static MainWindow Instance { get { return instance; } }

  private FileList fl = new fileList();

  private MainWindow() {
    InitializeComponent();
    fl.show();
  }
}

Your file list can then use MainWindow.Instance.

然后您的文件列表可以使用MainWindow.Instance.

But, this has the side-effect of partially hiding dependencies between the two classes. What you really want to do is require a MainWindowinstance in the constructor to fileList. That keeps the dependencies obvious, and opens the door to using a framework (which will help you with testability).

但是,这具有部分隐藏两个类之间的依赖关系的副作用。您真正想要做的是MainWindow在构造函数中需要一个实例以fileList. 这使依赖关系显而易见,并为使用框架打开了大门(这将帮助您进行可测试性)。

Also, the C# convention is to call the class FileListand not fileList.

此外,C# 约定是调用类FileList而不是fileList.

回答by Matosha

I do this to get a method to run inside one of my class's without doing the whole variable setup.

我这样做是为了让方法在我的一个类中运行,而无需进行整个变量设置。

string res = (new myClass ()).methodInsideMyclass ();