gpt4 book ai didi

c# - 将没有属性的类标记为可序列化是没有意义的吗?

转载 作者:行者123 更新时间:2023-11-30 18:56:02 24 4
gpt4 key购买 nike

我在处理代码库上的代码分析警告时遇到了这段代码。我想更改名称,但不会导致序列化问题。虽然在我看来将它序列化是没有意义的,但我只是想检查一下以确保在剥离属性之前我没有遗漏任何东西。

[Serializable]
public class FileIsNotReadonlyVerifier : IFileVerifier
{
#region IFileVerifier Members
public void Verify(FileInfo file, FlatFileTrafficSystem system)
{
if ((file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
throw new VerificationException(Resources.VerificationException_FileIsReadonly);
}
}
#endregion
}

最佳答案

是的,请将其标记为可序列化。原因是如果您不这样做,任何使用您的类型的人都将无法序列化此类的实例。

[Serializable] 
public class MyType {

// Breaks serialization.
private readonly FileIsNotReadonlyVerifier _verifier;

// Might work, might break. Depends on the implementation. Have to use
// another context variable to serialize / deserialize this.
private readonly IFileVerifier _otherVerifier;

}

在这种情况下让它工作的唯一方法是使变量不可序列化,使用另一个变量来跟踪状态,并使用修复逻辑覆盖特殊的序列化方法。

我已经多次遇到这个问题,这非常令人沮丧。最值得注意的是,我在人们创建没有成员的自定义字符串比较器的地方遇到过它。为了序列化我的类型,我不得不经历很多困难。非常令人沮丧。

关于c# - 将没有属性的类标记为可序列化是没有意义的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1139946/

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