Hola me estoy iniciando en la carrera de tecnico superior en programacion, bueno mi consulta es si como seria, el codigo para poder pedir en consola el valor de una variable, por ejemplo.. Ingrese un numero entero. Saludos!
creo que sería
Console.Writeline(variable)
de todas formas puedes repasarte estos tutoriales (http://www.csharpya.com.ar/) :P yo no se de c#, pero ese autor me ayufó mucho en los lenguajes web :P
Con ese codigo, creo q lo q haces es escribir una linea en la consola, con eso no puedo pedir un dato para almacenar en una variable
XD sorry! creí que pedías eso!
linea = Console.ReadLine();
de todas formas leete los tutoriales, esas son las cosas más basicas
Ya te dieron una solución rápida, pero ya puestos a introducir valores de un tipo específico... hagámoslo lo mejor posible!
[youtube=640,360]https://www.youtube.com/watch?v=j9fT9l-rPuE[/youtube]
Friend Module Test
Friend Num As Integer = -0I
Friend Sub Main()
Console.Title = "Introduciendo valores... By Elektro"
Console.WriteLine()
Num = ReadNumber(Of Integer)(
MaxValue:=Integer.MaxValue,
Mask:="."c,
CommentFormat:="[+] Introduce un valor {0} :",
IndicatorFormat:=" >> ",
DataTypeFormat:=New Dictionary(Of Type, String) From
{
{GetType(Integer),
String.Format("entero (Int32 Max: {0})", CStr(Integer.MaxValue))}
})
Console.WriteLine(Environment.NewLine)
Console.WriteLine(String.Format("Valor {0}: {1}", Num.GetType.Name, CStr(Num)))
Console.ReadKey()
Environment.Exit(0)
End Sub
' By Elektro
'
''' <summary>
''' Reads the console input to wait for an specific numeric value.
''' </summary>
''' <typeparam name="T"></typeparam>
''' <param name="MaxValue">Indicates the maximum value to expect.</param>
''' <param name="Mask">Indicates the character mask.</param>
''' <param name="CommentFormat">Indicates a comment string format.</param>
''' <param name="IndicatorFormat">Indicates a value indicator string format.</param>
''' <param name="DataTypeFormat">Indicates a data type string format.</param>
Friend Function ReadNumber(Of T)(Optional ByVal MaxValue As Object = -0S,
Optional ByVal Mask As Char = "",
Optional ByVal CommentFormat As String = "",
Optional ByVal IndicatorFormat As String = "",
Optional ByVal DataTypeFormat As Dictionary(Of Type, String) = Nothing) As T
' A temporal string that stores the value.
Dim TmpString As String = String.Empty
' Stores the current typed character.
Dim CurrentKey As New ConsoleKeyInfo("", ConsoleKey.NoName, False, False, False)
' Retrieve the numeric object Type.
Dim DataType As Type = GetType(T)
' Retrieve the Type name.
Dim ValueFormat As String = DataType.Name
' Retrieve the Type converter.
Dim Converter As System.ComponentModel.TypeConverter =
System.ComponentModel.TypeDescriptor.GetConverter(DataType)
' Set the maximum number value.
If Not CBool(MaxValue) Then
MaxValue = DataType.GetField("MaxValue").GetValue(Nothing)
End If
' Set the maximum number length.
Dim MaxValueLength As Integer = CStr(MaxValue).Length
' Set the indicator length.
Dim IndicatorLength As Integer = IndicatorFormat.Length
' Set the datatype name format.
If DataTypeFormat IsNot Nothing Then
ValueFormat = DataTypeFormat(DataType)
End If
' Write the comment.
If Not String.IsNullOrEmpty(CommentFormat) Then
Console.WriteLine(String.Format(CommentFormat, ValueFormat))
Console.WriteLine()
End If
' Write the indicator.
If Not String.IsNullOrEmpty(IndicatorFormat) Then
Console.Write(IndicatorFormat)
End If
' Write the value mask.
For X As Integer = 0 To MaxValueLength - 1
Console.Write(Mask)
Next
' Set the cursor at the start of the mask.
Console.SetCursorPosition(Console.CursorLeft - MaxValueLength, Console.CursorTop)
' Ready to parse characters!
Do
CurrentKey = Console.ReadKey(True)
Select Case CurrentKey.Key
Case ConsoleKey.Enter ' Accept the input.
Exit Do
Case ConsoleKey.Backspace ' Delete the last written character.
If Not String.IsNullOrEmpty(TmpString) Then
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop)
Console.Write(Mask)
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop)
TmpString = TmpString.ToString.Substring(0, TmpString.ToString.Length - 1)
End If
Case ConsoleKey.LeftArrow ' Move 1 cell to Left.
' Not implemented yet (Too much work deleting character in the current cursor position).
' Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop)
Case ConsoleKey.RightArrow ' Move 1 cell to Right.
' Not implemented yet (Too much work deleting character in the current cursor position).
' Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop)
Case Else ' Another key
Dim NextValue As String = If(Not String.IsNullOrEmpty(TmpString),
TmpString.ToString & CurrentKey.KeyChar,
CurrentKey.KeyChar)
' If value is valid and also does not exceed the maximum value then...
If Converter.IsValid(NextValue) _
AndAlso Not NextValue > MaxValue _
AndAlso Not NextValue.Length > MaxValueLength Then
TmpString = NextValue
Console.Write(CurrentKey.KeyChar)
End If
End Select
Loop
If Not String.IsNullOrEmpty(TmpString) Then ' Return the value.
Return Converter.ConvertFromString(TmpString)
Else
Return Nothing
End If
End Function
End Module
Traducción al vuelo a C# (no lo he testeado):
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
static internal class Test
{
static internal int Num = -0;
static internal void Main()
{
Console.Title = "Introduciendo valores... By Elektro";
Console.WriteLine();
Num = ReadNumber<int>(MaxValue: int.MaxValue, Mask: '.', CommentFormat: "[+] Introduce un valor {0} :", IndicatorFormat: " >> ", DataTypeFormat: new Dictionary<Type, string> { {
typeof(int),
string.Format("entero (Int32 Max: {0})", Convert.ToString(int.MaxValue))
} });
Console.WriteLine(Environment.NewLine);
Console.WriteLine(string.Format("Valor {0}: {1}", Num.GetType.Name, Convert.ToString(Num)));
Console.ReadKey();
Environment.Exit(0);
}
/// <summary>
/// Reads the console input to wait for an specific numeric value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="MaxValue">Indicates the maximum value to expect.</param>
/// <param name="Mask">Indicates the character mask.</param>
/// <param name="CommentFormat">Indicates a comment string format.</param>
/// <param name="IndicatorFormat">Indicates a value indicator string format.</param>
/// <param name="DataTypeFormat">Indicates a data type string format.</param>
static internal T ReadNumber<T>(object MaxValue = -0, char Mask = "", string CommentFormat = "", string IndicatorFormat = "", Dictionary<Type, string> DataTypeFormat = null)
{
// A temporal string that stores the value.
string TmpString = string.Empty;
// Stores the current typed character.
ConsoleKeyInfo CurrentKey = new ConsoleKeyInfo("", ConsoleKey.NoName, false, false, false);
// Retrieve the numeric object Type.
Type DataType = typeof(T);
// Retrieve the Type name.
string ValueFormat = DataType.Name;
// Retrieve the Type converter.
System.ComponentModel.TypeConverter Converter = System.ComponentModel.TypeDescriptor.GetConverter(DataType);
// Set the maximum number value.
if (!Convert.ToBoolean(MaxValue)) {
MaxValue = DataType.GetField("MaxValue").GetValue(null);
}
// Set the maximum number length.
int MaxValueLength = Convert.ToString(MaxValue).Length;
// Set the indicator length.
int IndicatorLength = IndicatorFormat.Length;
// Set the datatype name format.
if (DataTypeFormat != null) {
ValueFormat = DataTypeFormat(DataType);
}
// Write the comment.
if (!string.IsNullOrEmpty(CommentFormat)) {
Console.WriteLine(string.Format(CommentFormat, ValueFormat));
Console.WriteLine();
}
// Write the indicator.
if (!string.IsNullOrEmpty(IndicatorFormat)) {
Console.Write(IndicatorFormat);
}
// Write the value mask.
for (int X = 0; X <= MaxValueLength - 1; X++) {
Console.Write(Mask);
}
// Set the cursor at the start of the mask.
Console.SetCursorPosition(Console.CursorLeft - MaxValueLength, Console.CursorTop);
// Ready to parse characters!
do {
CurrentKey = Console.ReadKey(true);
switch (CurrentKey.Key) {
case ConsoleKey.Enter:
// Accept the input.
break; // TODO: might not be correct. Was : Exit Do
break;
case ConsoleKey.Backspace:
// Delete the last written character.
if (!string.IsNullOrEmpty(TmpString)) {
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
Console.Write(Mask);
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
TmpString = TmpString.ToString.Substring(0, TmpString.ToString.Length - 1);
}
break;
case ConsoleKey.LeftArrow:
// Move 1 cell to Left.
break;
// Not implemented yet (Too much work deleting character in the current cursor position).
// Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop)
case ConsoleKey.RightArrow:
// Move 1 cell to Right.
break;
// Not implemented yet (Too much work deleting character in the current cursor position).
// Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop)
default:
// Another key
string NextValue = !string.IsNullOrEmpty(TmpString) ? TmpString.ToString + CurrentKey.KeyChar : CurrentKey.KeyChar;
// If value is valid and also does not exceed the maximum value then...
if (Converter.IsValid(NextValue) && !(NextValue > MaxValue) && !(NextValue.Length > MaxValueLength)) {
TmpString = NextValue;
Console.Write(CurrentKey.KeyChar);
}
break;
}
} while (true);
// Return the value.
if (!string.IsNullOrEmpty(TmpString)) {
return Converter.ConvertFromString(TmpString);
} else {
return null;
}
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: @telerik
//Facebook: facebook.com/telerik
//=======================================================