Xamarin 如何从PCL项目访问iOS/Android项目代码中的方法

Xamarin 如何从PCL项目访问iOS/Android项目代码中的方法,xamarin,xamarin.forms,Xamarin,Xamarin.forms,在我的XamarinStudio for MAC中,我使用“Xamarin.Forms”解决方案。我有3个项目。PCL、iOS和Android。 我有一个proxyclass(webservice类),我将文件“checkServices.cs”复制到iOS和Android项目中。我还在“iOS”和“Android”项目中添加了System.Web.Webservices引用 PCL在iOS和Android中被引用,但不能反过来引用。共享是唯一的方式。来自PCL-->iOS/ANDROID 现在

在我的XamarinStudio for MAC中,我使用“Xamarin.Forms”解决方案。我有3个项目。PCL、iOS和Android。 我有一个proxyclass(webservice类),我将文件“checkServices.cs”复制到iOS和Android项目中。我还在“iOS”和“Android”项目中添加了System.Web.Webservices引用

PCL在iOS和Android中被引用,但不能反过来引用。共享是唯一的方式。来自PCL-->iOS/ANDROID


现在,我如何从PCL调用这些方法来将数据放在XAML页面上?我喜欢从位于iOS/Android项目文件夹中的PCL调用方法。

为此,您需要使用

简言之,在PCL中声明一个接口,该接口定义了要使用的方法,例如:

public interface ITextToSpeech
{
    void Speak (string text);
}
这可能是文本到语音实现的接口。现在,在特定于平台的项目中实现该接口。对于iOS,它可能看起来像这样:

using AVFoundation;

public class TextToSpeechImplementation : ITextToSpeech
{
    public TextToSpeechImplementation () {}

    public void Speak (string text)
    {
        var speechSynthesizer = new AVSpeechSynthesizer ();

        var speechUtterance = new AVSpeechUtterance (text) {
            Rate = AVSpeechUtterance.MaximumSpeechRate/4,
            Voice = AVSpeechSynthesisVoice.FromLanguage ("en-US"),
            Volume = 0.5f,
            PitchMultiplier = 1.0f
        };

        speechSynthesizer.SpeakUtterance (speechUtterance);
    }
}
这里是重要的部分:在名称空间上方用这个属性标记它<代码>[程序集:Xamarin.Forms.Dependency(typeof(TextToSpeechImplementation))]

您还需要将适当的using添加到项目中

现在,在运行时,根据您正在运行的平台,将为接口加载正确的实现。因此,对于Android,您的做法完全相同,只有
Speak
方法的实现会有所不同

在PCL中,您现在可以像这样访问它:
DependencyService.Get().Speak(“来自Xamarin表单的你好”)


您可能应该检查
DependencyService.Get()
方法是否不为null,以便在您出错时应用程序不会崩溃。但这应该包括基本内容。

你是最好的,也是最好中的最好。我花了将近两周的时间来制定我的问题并找到解决方案。。。。再次非常感谢你。。。。你是个救生员:)反过来呢,在Droid中调用PCL方法?不可能,因为这样会创建循环引用。从pcl公开事件或使用消息中心