我一直在尝试在 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
这是为此特定函数为我的库生成的 C# 代码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);
这样做的正确方法是什么?
最佳答案
我正在使用这个类来适应 Function1
由 Kotlin 绑定(bind)导出到 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) => {}));
附:ResponseType
是您输入参数的类别response
和 ErrorType
是您输入参数的类别error
.
关于c# - 将 Lambda 函数传递给 Xamarin.Android 绑定(bind)库中的 Kotlin 的 C# 生成代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64013415/