在Java中将类型转换为Java.Lang.Object转换为MonoDroid中的本机CLR类型

mir*_*ych 18 xamarin.android

如何将Java.Lang.Object转换为某种本机类型?

例:

ListView适配器包含本机类型Message的实例.当我试图从ListView获取SelectedItem时,它返回已转换为Java.Lang.Object的Message类型的实例,但是我找不到将Java.Lang.Object强制转换回Message的解决方案.

var message = (Message)list.SelectedItem;
// throws  Error    5   Cannot convert type 'Java.Lang.Object' to 'Message'
Run Code Online (Sandbox Code Playgroud)

请帮忙.

mir*_*ych 44

经过长时间的调配,找到了解决方案:

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

用法示例:

 var message = list.GetItemAtPosition(e.Position).Cast<Message>();
 bundle.PutInt("Message", message.ID);
Run Code Online (Sandbox Code Playgroud)

经过仔细的sdk研究,我们发现MonoDroid集成扩展用于此目的:

public static TResult JavaCast<TResult>(this Android.Runtime.IJavaObject instance)
where TResult : class, Android.Runtime.IJavaObject
Member of Android.Runtime.Extensions
Run Code Online (Sandbox Code Playgroud)


Jon*_*tes 9

从Spinner获取本机类型的最不可思议的方法是调用

    message = ((ArrayAdapter<Message>)list.Adapter).GetItem(list.SelectedItemPosition);
Run Code Online (Sandbox Code Playgroud)


小智 5

我从上面的答案中使用了这段代码,它对我来说很好

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

这就是我用的方式

var selectedLocation = locationSpinner.SelectedItem.Cast<Location>();
Run Code Online (Sandbox Code Playgroud)

我能够从微调器获得我的位置对象