[英]accessing non-static method from another class without instantiate
标题是我的问题。 我将在下面解释。
我正在研究WPF应用程序是vs2010。 我有两个窗口,一个是我的MainWindow,另一个是fileList窗口。 在我的fileList窗口中,我有一个文件列表,单击该文件即可加载文件。 onClick方法在fileList类中实现。 加载文件的功能在MainWindow子类中实现。
我的fileList类在MainWindow类中实例化以显示窗口。 我无法再次实例化MainWidow。 MainWindow中的函数(方法)无法声明为静态,因为它使用了我无法(不知道如何)声明为静态的其他参数。
我在下面粘贴相关代码。 请帮助。
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?
}
}
另一类:
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.
}
}
}
我衷心希望我清楚。 如果需要,请询问详细信息。
好吧,最简单的解决方案是为Filelist窗口提供一个构造函数,该构造函数接受一个委托,该委托指向Mainwindows中的processfile方法。 查看这篇文章: http : //www.codeproject.com/Articles/109000/C-Delegates-Step-by-Step
使其成为静态状态不是解决方案-这将是一个非常丑陋的hack,比委托产生更多的麻烦。
好的,这应该很容易。 您只需要在FileList类中声明一个事件,该事件会在Button_click方法中触发,该方法发送文件路径并从MainWindow进行预订,然后使用刚刚收到的参数调用processfile方法。
在您的FileList类中:
public event EventHandler<EventArgs<string>> PathReceived = delegate { };
将此发布在您的Button_click中。
在cosntructor的MainWindow类中:
this.fileList.PathReceived = (o,args) => this.ProcessFile(args.Value);
发布代码:
this.PathReceived(null, new EventArgs<string>(yourPath));
编辑:我忘了为您提供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; }
}
尽管这是一种反模式(因为它类似于全局变量并保持状态,这使测试更加困难),但您可以在此处使用单例模式:
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();
}
}
然后,您的文件列表可以使用MainWindow.Instance
。
但是,这具有部分隐藏两个类之间的依赖关系的副作用。 您真正想做的是在构造函数中需要一个MainWindow
实例到fileList
。 这样可以使依赖关系变得显而易见,并为使用框架打开了大门(这将有助于您进行可测试性测试)。
同样,C#约定是调用类FileList
而不是fileList
。
我这样做是为了让一种方法可以在我的一个类中运行,而无需进行整个变量设置。
string res = (new myClass ()).methodInsideMyclass ();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.