本文介绍了在派生类的构造函数中设置只读。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我知道不允许以下内容,但不应该这样吗? sharedObject是衍生的的一部分,应该能够在构造函数中设置 - 不是吗? tia 公共抽象类Base1 { protected readonly object sharedObject; } 公共类派生:Base1 { public Derived() { sharedObject = new object(); } } - William Stacey,MVP I know the following is not allowed, but shouldn''t it be? sharedObject ispart of Derived and should be able to be set in the constructor - no? tia public abstract class Base1{protected readonly object sharedObject; }public class Derived : Base1{ public Derived(){sharedObject = new object();} } --William Stacey, MVP 推荐答案 < snip> 除了Peter给出的答案之外,我还建议将任何 字段非私有至少*通常是一个坏主意。对于一次性课程来说,这不是很糟糕 ,或者可能是嵌套课程只能看到封闭课程的嵌套课程,但是我会避免使用它们其他。 - Jon Skeet - < sk *** @ pobox.com> http://www.pobox.com/~skeet 如果回复群组,请不要给我发邮件 <snip> As well as the answer given by Peter, I''d also suggest that making anyfields non-private is at least *usually* a bad idea. It''s not so badfor throwaway classes, or perhaps nested classes that are only visibleto the enclosing class, but I''d steer away from using them elsewhere. --Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeetIf replying to the group, please do not mail me too cpmsftngxa06.phx.gbl!TK2MSFTNGXA06 .phx.gbl!TK2MSFT NGXA05.phx.gbl!TK2MSFTNGP0 8.phx.gbl!TK2MSFTNGP09.phx.gbl cpmsftngxa06.phx.gbl!TK2MSFTNGXA06.phx.gbl!TK2MSFT NGXA05.phx.gbl!TK2MSFTNGP0 8.phx.gbl!TK2MSFTNGP09.phx.gbl 这篇关于在派生类的构造函数中设置只读。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-25 07:36