[英]Xamarin.Forms Dependency Service UWP: methodNotFoundException
[英]Xamarin.Forms Dependency Service non-static fields/properties
我正在使用Dependency Service获取特定于平台的接口实现。 假设我有以下界面:
public interface IMyInterface
{
bool IsEnabled { get; set; }
}
还有我的Android项目中的实现类:
[assembly: Dependency(typeof(MyClass))]
namespace App.Droid
{
class MyClass : IMyInterface
{
public bool IsEnabled { get; set; }
}
}
在代码的某个时刻,我将IsEnabled
设置为true
。
之后,我开始一个新活动,使我的应用程序进入后台:
Intent intent = new Intent();
intent.SetAction(action);
intent.SetFlags(ActivityFlags.NewTask);
MainActivity.Instance.StartActivity(intent);
当我的应用返回到前景时,我访问属性IsEnabled
并且得到false
而不是true
。 实际上,这是影响类的每个属性和私有字段发生的情况。 当我离开应用程序进行新活动时,这些属性会被垃圾回收吗?
我发现解决此问题的唯一方法是使所有后备字段均为static
,但这会增加代码的开销,如果我知道此行为的原因,这可能是不必要的。
不太了解您的问题的标题。
如果使用单例模式,则可以在需要时基于唯一的实例化对象提取属性,例如:
public class Singleton
{
// Define a static variable to hold an instance of the class
private static Singleton uniqueInstance;
// Define a private constructor so that the outside world cannot create instances of the class
private Singleton()
{
}
/// <summary>
/// Define public methods to provide a global access point, and you can also define public properties to provide global access points
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
// Create if the instance of the class does not exist, otherwise return directly
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
如果不是 ,则可以使用Properties
( https://docs.microsoft.com/zh-cn/dotnet/api/xamarin.forms.application.properties?view=xamarin-forms)访问数据。
private void SaveConnectionData(JSON.Connection C)
{
App.Current.Properties[Cryptography.Encryption("AccessToken")] = Cryptography.Encryption(C.Access_token);
App.Current.Properties[Cryptography.Encryption("ExpiresIn")] = Cryptography.Encryption(C.Expires_in.ToString());
App.Current.Properties[Cryptography.Encryption("TokenType")] = Cryptography.Encryption(C.Token_type);
App.Current.Properties[Cryptography.Encryption("Scope")] = Cryptography.Encryption(JsonConvert.SerializeObject(C.Scope));
App.Current.Properties[Cryptography.Encryption("RefreshToken")] = Cryptography.Encryption(C.Refresh_token);
App.Current.SavePropertiesAsync();
}
您可能参与了lifecycles
和notifications
的使用。此外,如果有大量数据,请考虑使用SQLite
数据库保存此数据。可以在此处引用此链接
更多信息 :在Xamarin.Android中,您还可以尝试lifecycles
来显示保存的数据。类似于OnResume
方法来显示数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.