简体   繁体   English

从不同的非静态类调用非静态方法

[英]Call non static method from different non static class

I have Mainpage.cs where I have method public void websocketRequestGetListOfUni() and then I have this class 我有Mainpage.cs,这里有方法public void websocketRequestGetListOfUni() ,然后有此类

public class RegisterResponseReceiverRegisterDevice : ResponseReceiver
    {
        public override void onResponseReceived(byte[] header, byte[] response)
        {
            RegisterResponse rr = RegisterResponse.ParseFrom(response);

            var t = new MainPage();
            t.websocketRequestGetListOfUni();
        }
        public override void onError() { }
    }

public void websocketRequestGetListOfUni()
    {
        IntMessage req = IntMessage.CreateBuilder().SetValue(1).Build();
        WebSocketClient.write(3, 7, req, new RegisterResponseReceiverGetListOfUni());
    }

I want call method websocketRequestGetListOfUni() in class RegisterResponseReceiverRegisterDevice but when I call it I get at var t = new MainPage(); 我想要在类RegisterResponseReceiverRegisterDevice调用方法websocketRequestGetListOfUni() ,但是当我调用它时,方法是var t = new MainPage();

error 错误

The application called an interface that was assigned to a different thread. 该应用程序调用了分配给其他线程的接口。

I also try use 我也尝试使用

this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => mymethoc);

but Dispather is not recognized. 但无法识别“无路者”。 Any idea how call my method? 知道如何调用我的方法吗?

here is Mainpage for better understanding: https://www.dropbox.com/s/oz6qb0naa0u0for/Mainpage.cs.txt 这是可以更好理解的主页: https : //www.dropbox.com/s/oz6qb0naa0u0for/Mainpage.cs.txt

var t = new MainPage(); is going to instanciate the page (including the UI part (which is instanciated by the Initialise call in MainPage constructor)) so it's a very bad idea to instanciate it just to get access to a method. 要实例化页面(包括UI部分(通过MainPage构造函数中的Initialize调用实例化)),因此实例化页面以仅访问方法是一个非常糟糕的主意。 I strongly sugest that you to reachitecture your code so that you don't need to do that. 我强烈建议您对代码进行结构化,这样就不必这样做了。 Particularly you should look at the MVVM patern. 特别是,您应该查看MVVM模式。

If you still want to do that, you can use the following code to dispatch your method on the UI thread: 如果仍然要这样做,则可以使用以下代码在UI线程上分派方法:

await CoreApplication.MainView.CoreWindow.RunAsync(CoreDispatcherPriority.Normal, () => mymethoc);

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

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