在C#中,可以使用注册表来存储.Net对象。以下是一个简单的示例,演示如何在注册表中存储和检索.Net对象:
using System;
[Serializable]
public class CustomObject
{
public string Name { get; set; }
public int Age { get; set; }
}
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.Win32;
public static void SaveObjectToRegistry(string keyName, object obj)
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, obj);
var objBytes = ms.ToArray();
Registry.CurrentUser.CreateSubKey(keyName).SetValue("CustomObject", objBytes);
}
}
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.Win32;
public static object GetObjectFromRegistry(string keyName)
{
var key = Registry.CurrentUser.OpenSubKey(keyName);
if (key == null)
{
return null;
}
var objBytes = key.GetValue("CustomObject") as byte[];
if (objBytes == null)
{
return null;
}
using (var ms = new MemoryStream(objBytes))
{
var bf = new BinaryFormatter();
return bf.Deserialize(ms);
}
}
现在,您可以使用这些方法将.Net对象存储在注册表中,并在需要时检索它们。例如:
var customObject = new CustomObject { Name = "John", Age = 30 };
SaveObjectToRegistry(@"Software\MyApp", customObject);
var retrievedObject = GetObjectFromRegistry(@"Software\MyApp") as CustomObject;
if (retrievedObject != null)
{
Console.WriteLine($"Name: {retrievedObject.Name}, Age: {retrievedObject.Age}");
}
请注意,这些方法仅适用于存储和检索.Net对象。如果您需要存储其他类型的数据,您可能需要使用其他方法。
领取专属 10元无门槛券
手把手带您无忧上云