代码之家  ›  专栏  ›  技术社区  ›  Unbreakable

如何在C#中只经过一些操作就将值传递给基构造函数

  •  2
  • Unbreakable  · 技术社区  · 6 年前

    How to pass value to base constructor

    public SMAPIException( string message) : base(message)
    {
        TranslationHelper instance = TranslationHelper.GetTranslationHelper; // singleton class
        string localizedErrMessage = instance.GetTranslatedMessage(message, "" );
        // code removed for brevity sake.
    }
    

    但是假设我想操作“消息”信息,然后设置基类构造函数,那么如何操作呢。

    伪代码如下:

    public SMAPIException( string message) : base(localizedErrMessage)
    {
        TranslationHelper instance = TranslationHelper.GetTranslationHelper; // singleton class
        string localizedErrMessage = instance.GetTranslatedMessage(message, "" );
        // code removed for brevity sake.
    }
    

    3 回复  |  直到 6 年前
        1
  •  4
  •   Felix D.    6 年前

    public class SMAPIException : Exception
    {
        public SMAPIException(string str) : base(ChangeString(str))
        {
            /*   Since SMAPIException derives from Exceptions we can use 
             *   all public properties of Exception
             */
            Console.WriteLine(base.Message);
        }
    
        private static string ChangeString(string message)
        {
            return $"Exception is: \"{message}\"";
        }
    }
    

    注意 那个 ChangeString 必须是 static !

    例子:

    SMAPIException ex = new SMAPIException("Here comes a new SMAPIException");
    
    //  OUTPUT //
    // Exception is "Here comes a new SMAPIException"     
    

    BaseType :

    // Summary:
    //     Initializes a new instance of the System.Exception class with a specified error
    //     message.
    //
    // Parameters:
    //   message:
    //     The message that describes the error.
    public Exception(string message);
    

    base(string message) 与相同 new Exception("message")

    Message -财产。

    但是! 这只适用于 SMAPIException 不隐藏其基本成员 new string Message {get; set;} !

        2
  •  2
  •   Felix D.    6 年前

    使用静态工厂方法,并将构造函数设为私有:

    class SMAPIException
    {
        private SMAPIException(string message) : base(message)
        {
            // whatever initialization
        }
    
        public static SMAPIException CreateNew(string message)
        {
            string localizedErrMessage;
            // do whatever to set localizedErrMessage
    
            return SMAPIException(localizedErrMessage);
        }
    }
    

    然后可以使用:

    SMAPIException localizedEx = SMAPIException.CreateNew("unlocalizedString");
    
        3
  •  0
  •   Antoine V    6 年前

    可以在基类构造函数的参数列表中调用静态方法。

    public SMAPIException( string message) 
          : base(TranslationHelper.GetTranslationHelper.GetTranslatedMessage(message, ""))
    {
    }
    
    推荐文章