无法访问静态背景下非静态方法? [英] Cannot access non-static method in static context?
问题描述
...
public class CalibrationViewModel : ViewModelBase
{
private FileSystemWatcher fsw;
public CalibrationViewModel(Calibration calibration)
{
fsw = new FileSystemWatcher
{
Path = @"C:\Users\user\Desktop\Path\ToFile\Test_1234.txt",
Filter = @"Test_1234.txt",
NotifyFilter = NotifyFilters.LastWrite
};
fsw.Changed += (o, e) =>
{
var lastLine = File.ReadAllLines(e.FullPath).Last();
Dispatcher.BeginInvoke((Action<string>) WriteLineToSamplesCollection, lastLine); //line that cites error
};
}
private void WriteLineToSamplesCollection(string line)
{
// do some work
}
}
为什么我得到错误,不能访问非静态方法的BeginInvoke在静态情况下'?
Why am I getting the error, 'Cannot access non-static method BeginInvoke in static context'?
我已经看了看SE其他几个例子,最举试图用一个字段创建对象之前,如果他们试图以静态方式使用非静态字段,但我不不懂它是什么我的代码被调用同样的错误。
I have looked at several other examples on SE and most cite trying to use a field before the object is created as if they were trying to use a non-static field in a static manner, but I don't understand what it is about my code that is invoking the same error.
最后,我能做些什么来解决这个具体问题/代码?
Lastly, what can I do to fix this specific issue/code?
更新:修正标题反映问题,以法而不是财产。我还补充说,类实现ViewModelBase。
Update: Fixed title to reflect issue with a 'method' and not a 'property'. I also added that the class implements ViewModelBase.
推荐答案
如果这是WPF, System.Windows.Threading程序.Dispatcher
没有一个静态的BeginInvoke()
方法。
If this is WPF, System.Windows.Threading.Dispatcher
does not have a static BeginInvoke()
method.
如果你想来调用静态(这是,无需分发程序实例本身的引用),你可以使用静态 Dispatcher.CurrentDispatcher
属性:
If you want to call that statically (this is, without having a reference to the Dispatcher instance itself), you may use the static Dispatcher.CurrentDispatcher
property:
Dispatcher.CurrentDispatcher.BeginInvoke(...etc);
要知道,虽然,从后台线程这样做会引用不返回UI线程的调度程序,而是创建一个说后台线程关联的新调度实例。
Be aware though, that doing this from a background thread will NOT return a reference to the "UI Thread"'s Dispatcher, but instead create a NEW Dispatcher instance associated with the said Background Thread.
一个访问更安全的方式UI线程的调度员可通过使用 System.Windows.Application.Current
静态属性的:
A more secure way to access the "UI Thread"'s Dispatcher is via the use of the System.Windows.Application.Current
static property:
Application.Current.Dispatcher.BeginInvoke(...etc);
这篇关于无法访问静态背景下非静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!