Calling the base constructor in C#

前端 未结 12 2859
南笙
南笙 2020-11-22 03:04

If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?

For exa

12条回答
  •  半阙折子戏
    2020-11-22 03:11

    From Framework Design Guidelines and FxCop rules.:

    1. Custom Exception should have a name that ends with Exception

        class MyException : Exception
    

    2. Exception should be public

        public class MyException : Exception
    

    3. CA1032: Exception should implements standard constructors.

    • A public parameterless constructor.
    • A public constructor with one string argument.
    • A public constructor with one string and Exception (as it can wrap another Exception).
    • A serialization constructor protected if the type is not sealed and private if the type is sealed. Based on MSDN:

      [Serializable()]
      public class MyException : Exception
      {
        public MyException()
        {
           // Add any type-specific logic, and supply the default message.
        }
      
        public MyException(string message): base(message) 
        {
           // Add any type-specific logic.
        }
        public MyException(string message, Exception innerException): 
           base (message, innerException)
        {
           // Add any type-specific logic for inner exceptions.
        }
        protected MyException(SerializationInfo info, 
           StreamingContext context) : base(info, context)
        {
           // Implement type-specific serialization constructor logic.
        }
      }  
      

    or

        [Serializable()]
        public sealed class MyException : Exception
        {
          public MyException()
          {
             // Add any type-specific logic, and supply the default message.
          }
    
          public MyException(string message): base(message) 
          {
             // Add any type-specific logic.
          }
          public MyException(string message, Exception innerException): 
             base (message, innerException)
          {
             // Add any type-specific logic for inner exceptions.
          }
          private MyException(SerializationInfo info, 
             StreamingContext context) : base(info, context)
          {
             // Implement type-specific serialization constructor logic.
          }
        }  
    

提交回复
热议问题