On Jul 9, 2012, at 1:26 AM, craig wrote:
> In the code below, in the setter for RawAdapter, I would like to cast/convert 
> the value variable from Java.Lang.Object to generic type T.

Are there any constraints on T?

> I have not found a simple way to do this.  In this example T must derive from 
> Android.Widget.IAdapter.

So you have this?

        where T : IAdapter

>        public abstract T Adapter { get; set; }
> 
>        protected override Java.Lang.Object RawAdapter
>        {
>            get
>            {
>                return Adapter.JavaCast<Java.Lang.Object>();
>            }
>            set
>            {
>                Adapter = value.JavaCast<T>(); //causes error

JavaCast<T>() is only needed when you need to perform Java-side object casts. 
The primary example being interface navigation, e.g. the EGLContext.EGL 
property [0] returns an instance of type IEGL [1], and you can't perform a C# 
runtime cast to e.g. IEGL11 [2] because the C# implementation for IEGL doesn't 
implement the IEGL11 interface, while the Java implementation of the EGL 
interface does. Because of this mismatch, Mono's type system must be "worked 
around" by using JavaCast<T>().

I don't think that your code requires JavaCast<T>(): you're not performing or 
requiring any Java-side interface navigation, so you should be able to use 
normal casts:

        protected override Java.Lang.Object RawAdapter {
                get {return (Java.Lang.Object) Adapter;}
                set {Adapter = (T) value;}
        }

The `get` cast should be fine, as all "sane" Java interface implementations 
will inherit Java.Lang.Object. (Failure to do so is generally a Bad Idea™.) The 
`set` should likewise be fine because if the type isn't coercible to a C# 'T' 
you'll want an exception anyway.

 - Jon

[0] 
http://androidapi.xamarin.com/?link=P%3aJavax.Microedition.Khronos.Egl.EGLContext.EGL

[1] http://androidapi.xamarin.com/?link=T:Javax.Microedition.Khronos.Egl.IEGL

[2] 
http://androidapi.xamarin.com/?link=T%3aJavax.Microedition.Khronos.Egl.IEGL11

_______________________________________________
Monodroid mailing list
[email protected]

UNSUBSCRIBE INFORMATION:
http://lists.ximian.com/mailman/listinfo/monodroid

Reply via email to