c# Public Nested Classes or Better Option?

后端 未结 8 633
青春惊慌失措
青春惊慌失措 2020-12-03 05:49

I have a control circuit which has multiple settings and may have any number of sensors attached to it (each with it\'s own set of settings). These sensors may only be used

8条回答
  •  遥遥无期
    2020-12-03 06:17

    I generally disagree with Eric on this.

    The thing I usually consider is: how often should the end user use the type name ControlCircuitLib.Sensor. If it's "almost never, but the type needs to be public so that doing something is possible", then go for inner types. For anything else, use a separate type.

    For example,

    public class Frobber {
        public readonly FrobType Standard = ...;
        public readonly FrobType Advanced = ...;
    
        public void Frob(FrobType type) { ... }
    
        public class FrobType { ... }
    }
    

    In this example, the FrobType only acts as an opaque 'thing'. Only Frobber needs to know what it actually is, although it needs to be possible to pass it around outside that class. However, this sort of example is quite rare; more often than not, you should prefer to avoid nested public classes.

    One of the most important things when designing a library is to keep it simple. So use whichever way makes the library and the using code simpler.

提交回复
热议问题