我正在尝试为专有的Android库生成Xamarin绑定(换句话说,不幸的是我不能在这里共享这个库)。但是我遇到了多态性的问题。情况就是这样。
该库公开了3个接口Location
,MobilityProfile
和Trip
都扩展了接口Reading
。
该库还有一个接口Measurement
,其中包含Reading getReading();
方法,该方法应始终返回上述3个接口之一(Location
,MobilityProfile
或Trip
)。
我生成了绑定并编译了运行良好的绑定项目。下一步是在我的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.");
}
}
现在,我最终处于default
条件,因为reading
参数的类型为IReadingInvoker
。有人可以建议我如何解决这个问题吗?
答案 0 :(得分:4)
Plz使用Android.Runtime.Extensions.JavaCast<ILocation>(readingInstace)
等等其他类型。
需要Probaly try-catch
。
干杯。
答案 1 :(得分:1)
因为您正在接收基本接口对象,所以switch语句无法将其识别为其他子接口之一。至少不是你期望它的方式。
根据你的评论和一些额外的检查,尝试下面的,并在每个的方括号中断点,只是为了确认它可以显式地转换为你的一个派生接口。
@RunWith(Parameterized.class)
class SomeTestClass{
@Mock
SomeTestClass mSomeTestClassInstance;
@Parameters
public static Object provideParameters() {
Object[] objects = new Object[]{
0,
0,
2
};
return objects;
}
public SomeTestClass(Object argument1){
mArgument1 = argument1;
}
@Test
public void testSomeMethod{
Object returnValue = mSomeTestClassInstance.testSomeMethod(mArgument1);
assertequals(mArgument1,returnValue)
}
}
绝对不是最好的方式。但是,由于此堆栈溢出问题中突出显示的原因,使用switch语句来确定类型有点不合时宜:Here.
编辑:在审核中看起来你需要一个显式的强制转换,这意味着你不能可靠地使用条件运算符,因为如果它不是显式强制转换会抛出异常能够施放物体。 Source.