Xamarin C# 无法将 c# 类转换为 Android.content.context

Met*_*ude 1 c# android xamarin.android

当我按下在共享代码项目中创建的按钮时,我试图通过显示来自 android 项目的警报对话框来测试我的应用程序的 DependencyService。

当我尝试通过在括号中输入 'this' 来设置 'AlertDialog.Builder' 中的 Context 属性时,我收到此错误:“无法从 'CallDiverter2.Droid.CallDiverter_Android' 转换为 'Android.Content.Context'。

命名空间也装饰有: '[assembly: Dependency(typeof(CallDiverter_Android))]' 如果它很重要。

这是我想使用 DependecyService 调用的 android 项目中的函数:

public class CallDiverter_Android : ICallDiverter
{
    public void DivertCall(string callForwardString)
    {
        //Divert call code

        //String callForwardString = "**21*1234567890#";
        //Intent callIntent = new Intent(Intent.ActionDial); // ACTION_CALL
        //Android.Net.Uri uri = Android.Net.Uri.Parse(callForwardString);
        //callIntent.SetData(uri);
        //Android.App.Application.Context.StartActivity(callIntent);


        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        AlertDialog alert = dialog.Create();
        alert.SetTitle("Title");
        alert.SetMessage("Simple Alert");
        alert.SetButton("OK", (s, ev) =>
        {
            alert.SetMessage("This is an alert message");
        });

        alert.Show();
    }

    public void StopCallDiverting()
    {
        //Stop the call diverting action
    }
}
Run Code Online (Sandbox Code Playgroud)

我应该如何解决这个问题,以便我可以成功测试dependencyService?

AAA*_*ddd 5

如果您只有一个活动应用程序,您可能只需传入即可

Android.App.Application.Context
Run Code Online (Sandbox Code Playgroud)

例如

AlertDialog.Builder dialog = new AlertDialog.Builder(Android.App.Application.Context);
Run Code Online (Sandbox Code Playgroud)

但是,要在多活动应用程序中获取当前活动上下文,则需要对其进行跟踪

请参阅此答案以了解如何跟踪当前上下文

/sf/answers/3315436491/