Xamarin.Android 绑定项目中的多态性

Mau*_*kom 3 c# binding xamarin.android

我正在尝试为专有的 Android 库生成 Xamarin 绑定(换句话说,不幸的是我无法在此处共享此库)。但是我遇到了多态性问题。情况是这样的。

该库公开了 3 个接口LocationMobilityProfile并且Trip都扩展了该接口Reading

该库还有一个接口Measurement,其中包含Reading getReading();应始终返回上述 3 个接口(LocationMobilityProfileTrip)之一的方法。

我生成了绑定并编译了运行良好的绑定项目。下一步是在我的 Xamarin 项目中使用 Xamarin.Android 绑定,如下所示:

public void ProcessReading(IReading reading)
{
    if (reading == null)
        return null;

    switch (reading)
    {
        case ILocation location:
            // Process location
            break;
        case IMobilityProfile mobilityProfile:
            // Process mobility profile
            break;
        case ITrip trip:
            // Process trip
            break;
        default:
            throw new NotSupportedException($"Processing the type '{reading.GetType().FullName}' is not supported.");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我最终陷入这种default情况,因为reading参数的类型是IReadingInvoker。有人可以建议我如何解决这个问题吗?

小智 5

当你的库以这种方式返回 Java 实例时,Xamarin.Android 绑定库无法将 Java 实例映射到其 C# 接口,因此转换永远不会起作用。

其他类型请使用Android.Runtime.Extensions.JavaCast<ILocation>(readingInstace)等等。

可能try-catch是需要的。

干杯。