【问题标题】:How to get byte value from IsolatedStorageSettings?如何从 IsolatedStorageSettings 中获取字节值?
【发布时间】:2012-01-23 17:26:30
【问题描述】:

就像在标题中我想要做的是从 IsolatedStorageSettings 中获取字节(类型)值

IsolatedStorageSettings isoSett = IsolatedStorageSettings.ApplicationSettings;
        if (isoSett.Contains("level") && isoSett.Contains("sound"))
        {
            bool dzwiek = (bool)isoSett["sound"];
            byte poziom = (byte)isoSett["level"];// here i get InvalidCastException
        }
        else 
        {
            isoSett.Add("level", 1);
            isoSett.Add("sound", true);
            isoSett.Save();
        }

我应该如何检索这个值? 感谢您的提前:)

编辑:在这个 InvalidCastException 下没有写其他内容

【问题讨论】:

  • InvalidCastException 的消息是什么?它认为它试图从什么进行投射?

标签: silverlight windows-phone-7


【解决方案1】:

看看这是否适合你:

从独立存储中保存通用对象

public void Save<T>(string fileName, T item)
{
    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(fileStream, item);
        }
    }
}

从独立存储中加载通用对象

public T Load<T>(string fileName)
{
    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            return (T)serializer.ReadObject(fileStream);
        }
    }
}

调用加载

string fileName = "SampleTest.txt";
byte level = 1;
Save<byte>(fileName, level);
byte value = Load<byte>(fileName);

【讨论】:

  • 这行得通,但我不需要为只包含 2 个简短信息而创建新文件,这就是我想使用 IsolatedStorageSettings 的原因
  • 是的....我明白了。为什么不制作一个对象并让它包含关卡和声音。然后将此对象保存到隔离存储中的单个条目中。这样做你有更多的控制权,你可以将不同的对象保存到不同的位置。
【解决方案2】:

您应该深入了解调试器,看看isoSett["level"] 实际上是什么

假设它是您保存它的 int 方式,但这不应该导致该转换失败。除非级别是一个更大的数字并且您溢出字节?

【讨论】:

  • 是的,这是从 int 转换为 byte 的问题。我不知道默认情况下数字 1 是 int。非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 2012-03-10
相关资源
最近更新 更多