【问题标题】:Pass Lambda function to C# generated code of Kotlin in Xamarin.Android binding library将 Lambda 函数传递给 Xamarin.Android 绑定库中的 Kotlin 的 C# 生成代码
【发布时间】:2021-01-22 17:10:20
【问题描述】:

我一直在尝试在 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);

这样做的正确方法是什么?

【问题讨论】:

  • 可以将 lambda 表达式转换为委托类型。但在您的情况下,lambda 表达式将转换为不支持的 'IFunction1' 类型。尝试传递 'IFunction1' 类型的参数。

标签: c# android kotlin xamarin xamarin.android


【解决方案1】:

我使用这个类是为了将 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 的类。

【讨论】:

    猜你喜欢
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2016-12-14
    相关资源
    最近更新 更多