2016-05-11 6 views
1

Ich habe eine Basis von Code geerbt, und ich möchte eine kleine Änderung ohne viel Refactoring für einige statische Funktionen in einer Klasse vornehmen, um mit Konfigurationsinformationen verwenden zu können.C# Globale Instanz einer statischen Klasse erstellen

Mein Problem ist, dass es eine statische Klasse gibt, die Funktionen für die Interaktion mit der Konsole hat. Diese statischen Funktionen können dann einfach mit der Console.Write() -Notation aufgerufen werden. Das Problem, das ich habe, ist, dass ich einige Konfigurationsänderungen in der statischen Klasse basierend auf Befehlszeilenoptionen vornehmen muss, die an das Hauptprogramm übergeben werden.

Während ich Dependency Injection normalerweise verwenden würde, um dies zu unterstützen, wird in der Codebasis keine Instanz dieser Klasse an Objekte übergeben, die sie verwenden. Ich muss eine Einstellung in der statischen Klasse zur Laufzeit konfigurieren, um zu steuern, wie die Funktionen in der Klasse funktionieren.

Ich weiß nicht, wie man das mit C# (und anderen Sprachen) macht, ohne die größere Änderung zu machen, um die Abhängigkeitsinjektion zu unterstützen.

Short Probe des statischen Klasse Zugriff

public class ConsoleUtilities 
{ 
    public static string ApplicationVersion 
    { 
     get 
     { 
      Assembly MyProgram = Assembly.GetEntryAssembly(); 
      return MyProgram.GetName().Version.ToString(); 
     } 
    } 

    /// <summary> 
    /// Show Text on the screen, and optionally write to LogPathFileName 
    /// </summary> 
    /// <param name="HelpText">Text to show</param> 
    /// <param name="LogPathFileName">Path and File Name of LogFile to write to. Use "" to not Log</param> 
    public static void ShowText(string[] HelpText, string LogPathFileName) 
    { 
     foreach (string HelpLine in HelpText) 
     { 
      ShowText(HelpLine, System.ConsoleColor.Gray, System.ConsoleColor.Black, LogPathFileName); 
     } 
    } 

    public static void ShowText(string HelpLine, System.ConsoleColor Foreground, System.ConsoleColor Background, string LogPathFileName) 
    { 
     ShowTextOnConsole(HelpLine, Foreground, Background, true, LogPathFileName); 
    } 
} 

Beispielprogramm der statische Klasse mit

public class Program 
{ 
    public enum EXIT_CODES { OK = 0, CONFIG_ERROR, FILE_ERROR, COMPARE_ERROR, EXECUTION_ERROR, WARNING }; 
    public const string LogPathFileName = "Tool.log"; 

    static int Main(string[] args) 
    { 
     int ApplicationExitCode = (int)EXIT_CODES.OK; 
     int Failures = 0; 

     string[] AboutText = { 
      "Tool.exe - " + CSharpUtilities.ConsoleUtilities.ApplicationVersion, 
      "Copyright (c) 2014", 
      "" 
     }; 

     Settings AppSettings = new Settings(AboutText); 

     // Ensure Command Line is valid before proceeding 
     ApplicationExitCode = (int)EXIT_CODES.CONFIG_ERROR; 
     ApplicationCommandLine AppCommandLine = new ApplicationCommandLine(); 

     try 
     { 
      if (AppCommandLine.ParseCommandLine(args)) 
      { 
       // Load Application Settings 
       LoadApplicationSettings(ref AppSettings, AppCommandLine); 
       ConsoleUtilities.ShowText(AboutText, LogPathFileName); 
       List<string> ValidationErrors = ValidateApplicationSettings(AppSettings); 
       if (ValidationErrors.Count == 0) 
       { 
        ... 
       } 
       else 
       { 
        ConsoleUtilities.ShowText(ValidationErrors.ToArray(), LogPathFileName); 
       } 
      } 
     } 

     catch (Exception e) 
     { 
      ApplicationExitCode = (int)EXIT_CODES.EXECUTION_ERROR;  // Exception occured in processing. Fail the program execution. 
      string[] SystemError = { "System Error", e.Message.ToString() }; 
      ConsoleUtilities.ShowText(SystemError, LogPathFileName); 
     } 

    } 
} 
+1

Fügen Sie der Klasse einige statische Felder/Eigenschaften hinzu? – Chris

+0

@Chris um klar zu sein, die Klasse wird nie irgendwo initialisiert. Kann ich diese Werte noch einstellen? Wenn ja, ist das erheblich einfacher. –

+1

Absolut. Eine statische Klasse wird bei der ersten Verwendung automatisch initialisiert. – Chris

Antwort

4

Sie statische Felder in der statischen Klasse setzen, und initialisieren Sie sie in Ihrem Programm nach dem Parsen Befehlszeile. Zum Beispiel:

public class ConsoleUtilities 
{ 
    public static bool ShowLog { get; set; } = true; // true, if we want log messages to be printed 

    public static void Log(string[] HelpText, string LogPathFileName) 
    { 
    if (ShowLog) { 
    foreach (string HelpLine in HelpText) 
    { 
     ShowText(HelpLine, System.ConsoleColor.Gray, System.ConsoleColor.Black, LogPathFileName); 
    } 
    } 
} 

}

Und dann, wenn Befehlszeile irgendwo in Ihrem Code Parsen würden Sie

ConsoleUtilities.ShowLog = true; // or false 
1

verwenden Sie können die Konfiguration als ein statisches Feld oder eine Eigenschaft aussetzen:

public class ConsoleUtilities 
{ 
    public static string ApplicationVersion 
    { 
     get 
     { 
      Assembly MyProgram = Assembly.GetEntryAssembly(); 
      return MyProgram.GetName().Version.ToString(); 
     } 
    } 

    public static ConsoleConfiguration Configuration = new ConsoleConfiguration(); 

    /// <summary> 
    /// Show Text on the screen, and optionally write to LogPathFileName 
    /// </summary> 
    /// <param name="HelpText">Text to show</param> 
    /// <param name="LogPathFileName">Path and File Name of LogFile to write to. Use "" to not Log</param> 
    public static void ShowText(string[] HelpText, string LogPathFileName) 
    { 
     foreach (string HelpLine in HelpText) 
     { 
      ShowText(HelpLine, Configuration.BackgroundColor, Configuration.ForegroundColor, LogPathFileName); 
     } 
    } 

    public static void ShowText(string HelpLine, System.ConsoleColor Foreground, System.ConsoleColor Background, string LogPathFileName) 
    { 
     ShowTextOnConsole(HelpLine, Foreground, Background, true, LogPathFileName); 
    } 
} 

public class ConsoleConfiguration 
{ 
    public ConsoleColor ForegroundColor { get; set; } 
    public ConsoleColor BackgroundColor { get; set; } 

    public ConsoleConfiguration() 
    { 
     ForegroundColor = ConsoleColor.Gray; 
     BackgroundColor = ConsoleColor.Black; 
    } 
} 

Und Sie können neu konfigurieren wie:

ConsoleUtilities.Configuration.ForegroundColor = ...