特定特性的属性进行序列化存取

本文介绍了如何在C#中通过自定义SerializableAttribute特性标记需要序列化的属性,并提供了一个示例,展示了如何使用自定义的SaveSettings和LoadSettings方法进行序列化和反序列化,仅处理带有该特性的属性。
摘要由CSDN通过智能技术生成

在C#中,如果你想对当前类中的特定特性的属性进行序列化和反序列化,你可以通过自定义一个特性(Attribute)来标记这些属性,并在序列化和反序列化的过程中仅处理这些带有特定特性的属性。以下是一个如何实现这一功能的例子:

首先,定义一个自定义特性,用于标记需要序列化的属性:

csharp
using System;

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SerializableAttribute : Attribute
{
}
然后,在你的类中,使用这个特性来标记需要序列化的属性:

csharp
public class MySettings
{
[Serializable]
public string Setting1 { get; set; }

[Serializable]  
public int Setting2 { get; set; }  

// 其他不需要序列化的属性  
public string NotSerializable { get; set; }  

}
现在,你需要编写自定义的序列化和反序列化方法,这些方法会检查属性上是否有SerializableAttribute特性,并仅处理这些属性:

csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

public class Serializer
{
public static void SaveSettings(T settings, string filePath) where T : class
{
var serializableProperties = typeof(T).GetProperties()
.Where(p => p.GetCustomAttribute() != null)
.ToList();

    using (var stream = new FileStream(filePath, FileMode.Create))  
    {  
        var binaryFormatter = new BinaryFormatter();  
        var dict = new Dictionary<string, object>();  

        foreach (var prop in serializableProperties)  
        {  
            dict.Add(prop.Name, prop.GetValue(settings));  
        }  

        binaryFormatter.Serialize(stream, dict);  
    }  
}  

public static T LoadSettings<T>(string filePath) where T : class, new()  
{  
    T settings = new T();  

    if (!File.Exists(filePath))  
    {  
        throw new FileNotFoundException("Settings file not found.", filePath);  
    }  

    using (var stream = new FileStream(filePath, FileMode.Open))  
    {  
        var binaryFormatter = new BinaryFormatter();  
        var dict = (Dictionary<string, object>)binaryFormatter.Deserialize(stream);  

        foreach (var kvp in dict)  
        {  
            var prop = typeof(T).GetProperty(kvp.Key);  
            if (prop != null && prop.GetCustomAttribute<SerializableAttribute>() != null)  
            {  
                prop.SetValue(settings, kvp.Value);  
            }  
        }  
    }  

    return settings;  
}  

}
现在,你可以使用这些方法来保存和加载带有SerializableAttribute特性的属性:

csharp
class Program
{
static void Main(string[] args)
{
string settingsFilePath = “settings.bin”;

    // 创建并保存设置  
    MySettings settings = new MySettings  
    {  
        Setting1 = "Value1",  
        Setting2 = 42,  
        NotSerializable = "This should not be serialized"  
    };  
    Serializer.SaveSettings(settings, settingsFilePath);  

    // 加载设置  
    MySettings loadedSettings = Serializer.LoadSettings<MySettings>(settingsFilePath);  
    Console.WriteLine($"Loaded Setting1: {loadedSettings.Setting1}");  
    Console.WriteLine($"Loaded Setting2: {loadedSettings.Setting2}");  
    // NotSerializable 属性应该没有被加载,保持默认值  
    Console.WriteLine($"Loaded NotSerializable: {loadedSettings.NotSerializable}");  
}  

}
在这个例子中,SaveSettings方法通过反射找到所有带有SerializableAttribute特性的属性,并将它们的名称和值保存到一个字典中,然后序列化这个字典到文件。LoadSettings方法则反序列化文件内容回字典,并设置到相应属性的值上。这样,只有带有SerializableAttribute特性的属性会被序列化和反序列化。

请注意,为了简化示例,这里使用了BinaryFormatter进行序列化和反序列化。然而,BinaryFormatter在某些情况下可能不安全,因此在实际应用中,你可能需要考虑使用更安全的序列化方法,如System.Text.Json或Newtonsoft.Json。此外,这个例子也假设了所有需要序列化的属性都是可以直接序列化的,如果属性是复杂类型或需要特殊处理,你可能需要在序列化和反序列化时添加

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值