问题描述
我一直试图在Xamarin项目中使用我的Android库(用Kotlin编写),但是我一直坚持将Lambda函数传递给C#生成的Kotlin代码
我正在尝试做这样的事情
client.DoSomething((response) => {},(error) => {});
但是我遇到了这个错误
CS1660: Cannot convert lambda expression to type 'IFunction1' because it is not a delegate type
using Android.Runtime;
using Java.Interop;
using java.lang;
using Kotlin.Jvm.Functions;
using System;
[Register ("doSomething","(Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;)V","")]
public unsafe void DoSomething (IFunction1 onSuccess,IFunction1 onFailure);
这样做的正确方法是什么?
解决方法
我使用这个类是为了将 Kotlin 绑定导出的 Function1
适配到 C# Lambda:
class Function1Impl<T> : Java.Lang.Object,IFunction1 where T : Java.Lang.Object
{
private readonly Action<T> OnInvoked;
public Function1Impl(Action<T> onInvoked)
{
this.OnInvoked = onInvoked;
}
public Java.Lang.Object Invoke(Java.Lang.Object objParameter)
{
try
{
T parameter = (T)objParameter;
OnInvoked?.Invoke(parameter);
return null;
}
catch (Exception ex)
{
// Exception handling,if needed
}
}
}
使用该类,您将能够执行以下操作:
client.DoSomething(new Function1Impl<ResponseType>((response) => {}),new Function1Impl<ErrorType>((error) => {}));
P.S.:ResponseType
是输入参数 response
的类,ErrorType
是输入参数 error
的类。