Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: override method in initialization

In android java if I want to use my view from not original thread I write so:

Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        String text = (String) msg.obj;
        myTextView.setText(text);
    }
};

And all works fine. But in xamarin C# I write:

Handler h = new Handler()
{
    public override void HandleMessage (Message msg)
    {

    }
};

and see invalid initializer member declarator

How to reload HandleMessage method? Can I use my view from another thread with any another way?


Edit: @AntP, this way does not work in xamarin: Only the original thread that created a view hierarchy can touch its views. But thanks for your support.

Solution:

mActivity.RunOnUiThread(delegate
{
    mTextView.Text = ("Test");
});
like image 835
Leo Avatar asked Oct 21 '22 10:10

Leo


1 Answers

You cannot override methods inside object initializers. You will have to declare a class that inherits Handler and overrides HandleMessage:

public class MyHandler : Handler
{
    public override void HandleMessage (Message msg)
    {
        // Some stuff
    }
}

From MSDN:

Anonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid. The expression that is used to initialize a property cannot be null, an anonymous function, or a pointer type.

Hence, anonymous types can only contain public properties. Not methods.

like image 184
Ant P Avatar answered Oct 24 '22 10:10

Ant P