简体   繁体   English

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

[英]accessing non-static method from another class without instantiate

Title is my question. 标题是我的问题。 I will explain below. 我将在下面解释。

I am working on wpf application is vs2010. 我正在研究WPF应用程序是vs2010。 I have two windows, one is my MainWindow and another is a fileList window. 我有两个窗口,一个是我的MainWindow,另一个是fileList窗口。 In my fileList window, I have a list of files, which on click, should load the file. 在我的fileList窗口中,我有一个文件列表,单击该文件即可加载文件。 The onClick method is implemented in fileList class. onClick方法在fileList类中实现。 The function to load the file is implemented in MainWindow partial class. 加载文件的功能在MainWindow子类中实现。

My fileList class in instantiated in MainWindow class to show the window. 我的fileList类在MainWindow类中实例化以显示窗口。 I cant instantiate MainWidow again. 我无法再次实例化MainWidow。 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. 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. 如果需要,请询问详细信息。

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. 好吧,最简单的解决方案是为Filelist窗口提供一个构造函数,该构造函数接受一个委托,该委托指向Mainwindows中的processfile方法。 Look at this article: http://www.codeproject.com/Articles/109000/C-Delegates-Step-by-Step 查看这篇文章: 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. 使其成为静态状态不是解决方案-这将是一个非常丑陋的hack,比委托产生更多的麻烦。

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 MainWindow type. 然后只需选择第一个(如果有多个,则找出合适的一个)并转换为MainWindow类型。 And now you have an instance to call your method. 现在,您有了一个实例来调用您的方法。

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: 在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; }
}

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 MainWindow instance in the constructor to fileList . 您真正想做的是在构造函数中需要一个MainWindow实例到fileList That keeps the dependencies obvious, and opens the door to using a framework (which will help you with testability). 这样可以使依赖关系变得显而易见,并为使用框架打开了大门(这将有助于您进行可测试性测试)。

Also, the C# convention is to call the class FileList and not fileList . 同样,C#约定是调用类FileList而不是fileList

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM