在 C# 中重写内在属性的继承

发布于 2024-09-13 13:32:56 字数 263 浏览 9 评论 0原文

在尝试序列化我的类和子类时与一堆未捕获的异常进行斗争之后,我终于明白了我的问题是什么:当应用于基类时,[Serialized] 不会被子类继承。一般来说,我对 C# 属性仍然很模糊,但我确实明白,在创建自定义属性时,程序员能够启用属性的自动继承。

有什么办法可以覆盖[Serialized]的继承吗?是否有任何充分的理由为什么没有从一开始就这样做和/或首先这样做是一个坏主意?我希望所述基类的所有子类都是可序列化的,因此必须将该属性添加到我创建的任何新子类中似乎不太优雅。

谢谢!

After wrestling with a bunch of uncaught exceptions when trying to serialize my classes and subclasses, I've finally understood what my problem had been: [Serializable] isn't inherited by subclasses when applied to a base class. I'm still really fuzzy about C# Attributes in general, but I do understand that when creating a custom Attribute, the programmer is able to enable automatic inheritance of the Attribute.

It there any way to override the inheritance of [Serializable]? Is there any good reason why it wasn't done from the start and/or would be a bad idea to do this in the first place? I would want all subclasses of said base class be serializable, so it just seems inelegant to have to add the attribute to any new subclasses I make.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

长途伴 2024-09-20 13:32:56

首先没有这样做绝对是有充分理由的 - 仅仅因为基类是可序列化的并不意味着派生类自然是可序列化的。

哎呀,object 是可序列化的 - 如果可序列化性被继承,那就意味着 .NET 中的每个类都将是可序列化的:)

你也不能“覆盖”它 - 你必须在每个类上指定它。实际上,我认为这是一件好事 - 当您添加属性时,您应该对类进行心理检查,并检查序列化它是否确实有意义。

There's absolutely a good reason it wasn't done in the first place - just because a base class is serializable doesn't mean that a derived class naturally is.

Heck, object is serializable - if serializability were inherited, that would mean every class in .NET would be serializable :)

You can't "override" that either - you have to specify it on every class. I think that's a good thing, actually - when you add the attribute, you should perform a mental check on the class and check that it really does make sense to serialize it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文