gpt4 book ai didi

c# - 从共享项目中获取嵌入式资源

转载 作者:行者123 更新时间:2023-12-05 02:14:42 24 4
gpt4 key购买 nike

我正在开发一个 Xamarin Forms 应用程序,它有两个项目,一个 Android 应用程序和一个 iOS 应用程序。所有其他代码都存储在共享项目中。

解决方案如下所示:

  • MyApp.Android(Android 项目),引用 MyApp.Base
  • MyApp.iOS(iOS 项目),引用 MyApp.Base
  • MyApp.Base(共享项目)

我正在使用以下代码从共享项目中读取 SVG 图像:

using (var stream = GetType().Assembly.GetManifestResourceStream("MyApp.Base.image.svg"))
{
// do work here...
}

当图像在 Android 或 iOS 项目中时,这非常有效,但我希望共享图像,所以我将其放在共享项目中。

GetType().Assembly 返回 MyApp.Android,因此找不到图像。我想我忽略了一些东西,但我一直无法找到解决方案。

谁能指出我正确的方向?谢谢!

最佳答案

您使用的是共享项目,而不是 PCL 或 .Net 标准库。因此,当您编译它们时,您所有的共享项目内容都将合并到特定于平台的项目中。这意味着 - 即使您将资源嵌入到 MyApp.Base 中,它也会被合并到 .iOS/.Droid 项目中。我建议您了解更多关于 Shared Project 与 PCL 或 .Net Standard 库的信息。下面的代码;我没有测试,但这是你应该遵循的方向:

#if __IOS__
var resourcePrefix = "MyApp.iOS.";
#endif
#if __ANDROID__
var resourcePrefix = "MyApp.Android.";
#endif

var assembly = IntrospectionExtensions.GetTypeInfo(typeof(SharedPage)).Assembly;
Stream stream = assembly.GetManifestResourceStream
(resourcePrefix + "image.svg");

有关更多信息,请查看此页面:https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/files?tabs=macos#embedding-in-shared-projects

关于c# - 从共享项目中获取嵌入式资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53326784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com