Type cast from Java.Lang.Object to native CLR type in MonoDroid

前端 未结 8 1159
花落未央
花落未央 2021-02-02 13:38

How to cast Java.Lang.Object to some native type?

Example:

ListView adapter contains instances of native type Message. When i am trying to get SelectedItem from

8条回答
  •  遇见更好的自我
    2021-02-02 14:00

    After long time debuging, have found the solution:

    public static class ObjectTypeHelper
    {
        public static T Cast(this Java.Lang.Object obj) where T : class
        {
            var propertyInfo = obj.GetType().GetProperty("Instance");
            return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
        }
    }
    

    Usage example:

     var message = list.GetItemAtPosition(e.Position).Cast();
     bundle.PutInt("Message", message.ID);
    

    After careful sdk study have found MonoDroid integrated extension for this purpose:

    public static TResult JavaCast(this Android.Runtime.IJavaObject instance)
    where TResult : class, Android.Runtime.IJavaObject
    Member of Android.Runtime.Extensions
    

提交回复
热议问题