2009-10-31 6 views
12

Come è possibile impostare un valore di input predefinito in un'app console .net?Come impostare il valore di input predefinito in .Net Console App?

Ecco il codice finzione:

Console.Write("Enter weekly cost: "); 
string input = Console.ReadLine("135"); // 135 is the default. The user can change or press enter to accept 
decimal weeklyCost = decimal.Parse(input); 

Naturalmente, non mi aspetto che sia così semplice. Sto scommettendo sul dover fare alcune cose non gestite di basso livello; Io proprio non so come.

EDIT

so di poter sostituire nessun ingresso con il default. Non è quello che sto chiedendo. Sto cercando di IMPARARE ciò che è implicato nel raggiungimento del comportamento che ho descritto: dare all'utente un valore predefinito modificabile. Inoltre non sono preoccupato per la convalida dell'input; la mia domanda non ha nulla a che fare con questo.

+0

È possibile codificare questa come la risposta suggerito - l'utente non si cura della tecnica di codifica. Per la domanda teorica se c'è un modo per farlo con readline - probabilmente no (almeno non documentato). – Dani

+0

Ma - Vedo che stavi cercando di andare, stiamo cercando una soluzione che permetta all'utente di cambiare il testo predefinito. – Dani

+0

So che non può essere fatto con. ReadLine(). Ma so che c'è un modo per farlo. –

risposta

5

credo che si dovrà gestire questo manualmente con l'ascolto di ogni pressione di un tasto:

thown rapidamente insieme esempio:

// write the initial buffer 
    char[] buffer = "Initial text".ToCharArray(); 
    Console.WriteLine(buffer); 

    // ensure the cursor starts off on the line of the text by moving it up one line 
    Console.SetCursorPosition(Console.CursorLeft + buffer.Length, Console.CursorTop - 1); 

    // process the key presses in a loop until the user presses enter 
    // (this might need to be a bit more sophisticated - what about escape?) 
    ConsoleKeyInfo keyInfo = Console.ReadKey(true); 
    while (keyInfo.Key != ConsoleKey.Enter) 
    { 

     switch (keyInfo.Key) 
     { 
      case ConsoleKey.LeftArrow: 
        ... 
       // process the left key by moving the cursor position 
       // need to keep track of the position in the buffer 

     // if the user presses another key then update the text in our buffer 
     // and draw the character on the screen 

     // there are lots of cases that would need to be processed (backspace, delete etc) 
     } 
     keyInfo = Console.ReadKey(true); 
    } 

Questo è abbastanza coinvolto - si dovrà tenere garantire il cursore non va fuori portata e aggiornare manualmente il buffer.

+0

Non penso che questo sia il significato della domanda. – driis

+0

In realtà questa è sicuramente la migliore risposta finora. –

+0

Getta questo in un metodo di estensione in modo da poter chiamare Console.ReadLine ("135"); I metodi di estensione possono essere sovraccarichi di metodi esistenti? In caso contrario, dargli un nuovo nome. – CoderDennis

3

Oppure ... Basta testare il valore inserito, se è vuoto metti il ​​valore predefinito in ingresso.

+0

per migliorare l'aspetto: puoi utilizzare una proprietà e aggiungerla al setter .... – Dani

1

soluzione semplice, se input dell'utente nulla, assegnare il default:

Console.Write("Enter weekly cost: "); 
string input = Console.ReadLine(); 
decimal weeklyCost = String.IsNullOrEmpty(input) ? 135 : decimal.Parse(input); 

Quando si tratta di input dell'utente, si dovrebbe aspettare che potrebbe contenere degli errori. Così si potrebbe utilizzare TryParse al fine di evitare un'eccezione, se l'utente non ha un numero di ingresso:

Console.Write("Enter weekly cost: "); 
string input = Console.ReadLine(); 
decimal weeklyCost; 
if (!Decimal.TryParse(input, out weeklyCost)) 
    weeklyCost = 135; 

questo sarebbe considerato best practice per la gestione di input dell'utente. Se è necessario analizzare molti input utente, utilizzare una funzione di supporto per quello. Un modo per farlo è usare un metodo con un nullable e restituire null se l'analisi fallisce. Allora è molto facile assegnare un valore predefinito utilizzando il null coalescing operator:

public static class SafeConvert 
{ 
    public static decimal? ToDecimal(string value) 
    { 
     decimal d; 
     if (!Decimal.TryParse(value, out d)) 
      return null; 
     return d; 
    } 
} 

Poi, per leggere un input e assegnare un valore di default è facile come:

decimal d = SafeConvert.ToDecimal(Console.ReadLine()) ?? 135; 
+0

Hai lasciato il suo parametro fittizio a 'ReadLine' in posizione. –

+0

@Adam, grazie per averlo indicato, risposta modificato. – driis

0

È possibile utilizzare metodo di supporto come questo:

public static string ReadWithDefaults(string defaultValue) 
{ 
    string str = Console.ReadLine(); 
    return String.IsNullOrEmpty(str) ? defaultValue : str; 
} 
6

Ecco una soluzione semplice:

public static string ConsoleReadLineWithDefault(string defaultValue) 
{ 
    System.Windows.Forms.SendKeys.SendWait(defaultValue); 
    return Console.ReadLine(); 
} 

Non è tuttavia completare. Alcuni caratteri nella stringa di input SendWait hanno un significato speciale in modo da doverli sfuggire (ad esempio +, (,), ecc.) Vedere: http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx per una descrizione completa.

2
  1. Aggiungi riferimento all'Assemblea Libreria "System.Windows.Forms" al progetto
  2. Aggiungi SendKeys.SendWait ("DefaultText") subito dopo il vostro comando Console.WriteLine e prima della Console.Comando ReadLine

 

string _weeklycost = ""; 
Console.WriteLine("Enter weekly cost: "); 
System.Windows.Forms.SendKeys.SendWait("135"); 
_weeklycost = Console.ReadLine(); 
Problemi correlati