仅在进行一些操作后才能将值传递给C#中的基本构造函数

时间:2018-09-07 14:03:16

标签: c# .net

好的,这个问题已经用SO回答了,这里是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.
}

//所以基本上我希望将localizedErrMessage而不是消息发送给基类构造函数,这可能吗?请引导我。

3 个答案:

答案 0 :(得分:4)

这应该有效:

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-Property获得传递的值。

但!仅在SMAPIException不隐藏其基本成员new string Message {get; set;}

时有效

答案 1 :(得分:2)

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

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");

答案 2 :(得分:0)

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

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