Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: estebankpo15 en 3 Abril 2014, 04:06 am



Título: Ayuda con consulta noob de C#.
Publicado por: estebankpo15 en 3 Abril 2014, 04:06 am
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!


Título: Re: Ayuda con consulta noob de C#.
Publicado por: engel lex en 3 Abril 2014, 04:11 am
creo que sería

Código
  1. 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


Título: Re: Ayuda con consulta noob de C#.
Publicado por: estebankpo15 en 3 Abril 2014, 04:28 am
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


Título: Re: Ayuda con consulta noob de C#.
Publicado por: engel lex en 3 Abril 2014, 04:31 am
XD sorry! creí que pedías eso!

Código
  1. linea = Console.ReadLine();

de todas formas leete los tutoriales, esas son las cosas más basicas


Título: Re: Ayuda con consulta noob de C#.
Publicado por: Eleкtro en 3 Abril 2014, 09:37 am
Ya te dieron una solución rápida, pero ya puestos a introducir valores de un tipo específico... hagámoslo lo mejor posible!

j9fT9l-rPuE

Código
  1. Friend Module Test
  2.  
  3.    Friend Num As Integer = -0I
  4.  
  5.    Friend Sub Main()
  6.  
  7.        Console.Title = "Introduciendo valores... By Elektro"
  8.        Console.WriteLine()
  9.  
  10.        Num = ReadNumber(Of Integer)(
  11.                         MaxValue:=Integer.MaxValue,
  12.                         Mask:="."c,
  13.                         CommentFormat:="[+] Introduce un valor {0} :",
  14.                         IndicatorFormat:=" >> ",
  15.                         DataTypeFormat:=New Dictionary(Of Type, String) From
  16.                                         {
  17.                                             {GetType(Integer),
  18.                                              String.Format("entero (Int32 Max: {0})", CStr(Integer.MaxValue))}
  19.                                         })
  20.  
  21.        Console.WriteLine(Environment.NewLine)
  22.        Console.WriteLine(String.Format("Valor {0}: {1}", Num.GetType.Name, CStr(Num)))
  23.        Console.ReadKey()
  24.  
  25.        Environment.Exit(0)
  26.  
  27.    End Sub
  28.  
  29.    ' By Elektro
  30.    '
  31.    ''' <summary>
  32.    ''' Reads the console input to wait for an specific numeric value.
  33.    ''' </summary>
  34.    ''' <typeparam name="T"></typeparam>
  35.    ''' <param name="MaxValue">Indicates the maximum value to expect.</param>
  36.    ''' <param name="Mask">Indicates the character mask.</param>
  37.    ''' <param name="CommentFormat">Indicates a comment string format.</param>
  38.    ''' <param name="IndicatorFormat">Indicates a value indicator string format.</param>
  39.    ''' <param name="DataTypeFormat">Indicates a data type string format.</param>
  40.    Friend Function ReadNumber(Of T)(Optional ByVal MaxValue As Object = -0S,
  41.                                     Optional ByVal Mask As Char = "",
  42.                                     Optional ByVal CommentFormat As String = "",
  43.                                     Optional ByVal IndicatorFormat As String = "",
  44.                                     Optional ByVal DataTypeFormat As Dictionary(Of Type, String) = Nothing) As T
  45.  
  46.        ' A temporal string that stores the value.
  47.        Dim TmpString As String = String.Empty
  48.  
  49.        ' Stores the current typed character.
  50.        Dim CurrentKey As New ConsoleKeyInfo("", ConsoleKey.NoName, False, False, False)
  51.  
  52.        ' Retrieve the numeric object Type.
  53.        Dim DataType As Type = GetType(T)
  54.  
  55.        ' Retrieve the Type name.
  56.        Dim ValueFormat As String = DataType.Name
  57.  
  58.        ' Retrieve the Type converter.
  59.        Dim Converter As System.ComponentModel.TypeConverter =
  60.            System.ComponentModel.TypeDescriptor.GetConverter(DataType)
  61.  
  62.        ' Set the maximum number value.
  63.        If Not CBool(MaxValue) Then
  64.            MaxValue = DataType.GetField("MaxValue").GetValue(Nothing)
  65.        End If
  66.  
  67.        ' Set the maximum number length.
  68.        Dim MaxValueLength As Integer = CStr(MaxValue).Length
  69.  
  70.        ' Set the indicator length.
  71.        Dim IndicatorLength As Integer = IndicatorFormat.Length
  72.  
  73.        ' Set the datatype name format.
  74.        If DataTypeFormat IsNot Nothing Then
  75.            ValueFormat = DataTypeFormat(DataType)
  76.        End If
  77.  
  78.        ' Write the comment.
  79.        If Not String.IsNullOrEmpty(CommentFormat) Then
  80.            Console.WriteLine(String.Format(CommentFormat, ValueFormat))
  81.            Console.WriteLine()
  82.        End If
  83.  
  84.        ' Write the indicator.
  85.        If Not String.IsNullOrEmpty(IndicatorFormat) Then
  86.            Console.Write(IndicatorFormat)
  87.        End If
  88.  
  89.        ' Write the value mask.
  90.        For X As Integer = 0 To MaxValueLength - 1
  91.            Console.Write(Mask)
  92.        Next
  93.  
  94.        ' Set the cursor at the start of the mask.
  95.        Console.SetCursorPosition(Console.CursorLeft - MaxValueLength, Console.CursorTop)
  96.  
  97.        ' Ready to parse characters!
  98.        Do
  99.  
  100.            CurrentKey = Console.ReadKey(True)
  101.  
  102.            Select Case CurrentKey.Key
  103.  
  104.                Case ConsoleKey.Enter ' Accept the input.
  105.                    Exit Do
  106.  
  107.                Case ConsoleKey.Backspace ' Delete the last written character.
  108.  
  109.                    If Not String.IsNullOrEmpty(TmpString) Then
  110.                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop)
  111.                        Console.Write(Mask)
  112.                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop)
  113.                        TmpString = TmpString.ToString.Substring(0, TmpString.ToString.Length - 1)
  114.                    End If
  115.  
  116.                Case ConsoleKey.LeftArrow ' Move 1 cell to Left.
  117.                    ' Not implemented yet (Too much work deleting character in the current cursor position).
  118.                    ' Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop)
  119.  
  120.                Case ConsoleKey.RightArrow ' Move 1 cell to Right.
  121.                    ' Not implemented yet (Too much work deleting character in the current cursor position).
  122.                    ' Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop)
  123.  
  124.                Case Else ' Another key
  125.  
  126.                    Dim NextValue As String = If(Not String.IsNullOrEmpty(TmpString),
  127.                                                 TmpString.ToString & CurrentKey.KeyChar,
  128.                                                 CurrentKey.KeyChar)
  129.  
  130.                    ' If value is valid and also does not exceed the maximum value then...
  131.                    If Converter.IsValid(NextValue) _
  132.                        AndAlso Not NextValue > MaxValue _
  133.                        AndAlso Not NextValue.Length > MaxValueLength Then
  134.  
  135.                        TmpString = NextValue
  136.                        Console.Write(CurrentKey.KeyChar)
  137.  
  138.                    End If
  139.  
  140.            End Select
  141.  
  142.        Loop
  143.  
  144.        If Not String.IsNullOrEmpty(TmpString) Then ' Return the value.
  145.            Return Converter.ConvertFromString(TmpString)
  146.        Else
  147.            Return Nothing
  148.        End If
  149.  
  150.    End Function
  151.  
  152. End Module


Traducción al vuelo a C# (no lo he testeado):

Código
  1. using Microsoft.VisualBasic;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Diagnostics;
  7. static internal class Test
  8. {
  9.  
  10.  
  11. static internal int Num = -0;
  12.  
  13. static internal void Main()
  14. {
  15. Console.Title = "Introduciendo valores... By Elektro";
  16. Console.WriteLine();
  17.  
  18. Num = ReadNumber<int>(MaxValue: int.MaxValue, Mask: '.', CommentFormat: "[+] Introduce un valor {0} :", IndicatorFormat: " >> ", DataTypeFormat: new Dictionary<Type, string> { {
  19. typeof(int),
  20. string.Format("entero (Int32 Max: {0})", Convert.ToString(int.MaxValue))
  21. } });
  22.  
  23. Console.WriteLine(Environment.NewLine);
  24. Console.WriteLine(string.Format("Valor {0}: {1}", Num.GetType.Name, Convert.ToString(Num)));
  25. Console.ReadKey();
  26.  
  27. Environment.Exit(0);
  28.  
  29. }
  30.  
  31. /// <summary>
  32. /// Reads the console input to wait for an specific numeric value.
  33. /// </summary>
  34. /// <typeparam name="T"></typeparam>
  35. /// <param name="MaxValue">Indicates the maximum value to expect.</param>
  36. /// <param name="Mask">Indicates the character mask.</param>
  37. /// <param name="CommentFormat">Indicates a comment string format.</param>
  38. /// <param name="IndicatorFormat">Indicates a value indicator string format.</param>
  39. /// <param name="DataTypeFormat">Indicates a data type string format.</param>
  40. static internal T ReadNumber<T>(object MaxValue = -0, char Mask = "", string CommentFormat = "", string IndicatorFormat = "", Dictionary<Type, string> DataTypeFormat = null)
  41. {
  42.  
  43. // A temporal string that stores the value.
  44. string TmpString = string.Empty;
  45.  
  46. // Stores the current typed character.
  47. ConsoleKeyInfo CurrentKey = new ConsoleKeyInfo("", ConsoleKey.NoName, false, false, false);
  48.  
  49. // Retrieve the numeric object Type.
  50. Type DataType = typeof(T);
  51.  
  52. // Retrieve the Type name.
  53. string ValueFormat = DataType.Name;
  54.  
  55. // Retrieve the Type converter.
  56. System.ComponentModel.TypeConverter Converter = System.ComponentModel.TypeDescriptor.GetConverter(DataType);
  57.  
  58. // Set the maximum number value.
  59. if (!Convert.ToBoolean(MaxValue)) {
  60. MaxValue = DataType.GetField("MaxValue").GetValue(null);
  61. }
  62.  
  63. // Set the maximum number length.
  64. int MaxValueLength = Convert.ToString(MaxValue).Length;
  65.  
  66. // Set the indicator length.
  67. int IndicatorLength = IndicatorFormat.Length;
  68.  
  69. // Set the datatype name format.
  70. if (DataTypeFormat != null) {
  71. ValueFormat = DataTypeFormat(DataType);
  72. }
  73.  
  74. // Write the comment.
  75. if (!string.IsNullOrEmpty(CommentFormat)) {
  76. Console.WriteLine(string.Format(CommentFormat, ValueFormat));
  77. Console.WriteLine();
  78. }
  79.  
  80. // Write the indicator.
  81. if (!string.IsNullOrEmpty(IndicatorFormat)) {
  82. Console.Write(IndicatorFormat);
  83. }
  84.  
  85. // Write the value mask.
  86. for (int X = 0; X <= MaxValueLength - 1; X++) {
  87. Console.Write(Mask);
  88. }
  89.  
  90. // Set the cursor at the start of the mask.
  91. Console.SetCursorPosition(Console.CursorLeft - MaxValueLength, Console.CursorTop);
  92.  
  93. // Ready to parse characters!
  94.  
  95. do {
  96. CurrentKey = Console.ReadKey(true);
  97.  
  98. switch (CurrentKey.Key) {
  99.  
  100. case ConsoleKey.Enter:
  101. // Accept the input.
  102. break; // TODO: might not be correct. Was : Exit Do
  103.  
  104.  
  105. break;
  106. case ConsoleKey.Backspace:
  107. // Delete the last written character.
  108.  
  109. if (!string.IsNullOrEmpty(TmpString)) {
  110. Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
  111. Console.Write(Mask);
  112. Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
  113. TmpString = TmpString.ToString.Substring(0, TmpString.ToString.Length - 1);
  114. }
  115.  
  116. break;
  117. case ConsoleKey.LeftArrow:
  118. // Move 1 cell to Left.
  119. break;
  120. // Not implemented yet (Too much work deleting character in the current cursor position).
  121. // Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop)
  122.  
  123. case ConsoleKey.RightArrow:
  124. // Move 1 cell to Right.
  125. break;
  126. // Not implemented yet (Too much work deleting character in the current cursor position).
  127. // Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop)
  128.  
  129. default:
  130. // Another key
  131.  
  132. string NextValue = !string.IsNullOrEmpty(TmpString) ? TmpString.ToString + CurrentKey.KeyChar : CurrentKey.KeyChar;
  133.  
  134. // If value is valid and also does not exceed the maximum value then...
  135.  
  136. if (Converter.IsValid(NextValue) && !(NextValue > MaxValue) && !(NextValue.Length > MaxValueLength)) {
  137. TmpString = NextValue;
  138. Console.Write(CurrentKey.KeyChar);
  139.  
  140. }
  141.  
  142. break;
  143. }
  144.  
  145. } while (true);
  146.  
  147. // Return the value.
  148. if (!string.IsNullOrEmpty(TmpString)) {
  149. return Converter.ConvertFromString(TmpString);
  150. } else {
  151. return null;
  152. }
  153.  
  154. }
  155.  
  156. }
  157.  
  158. //=======================================================
  159. //Service provided by Telerik (www.telerik.com)
  160. //Conversion powered by NRefactory.
  161. //Twitter: @telerik
  162. //Facebook: facebook.com/telerik
  163. //=======================================================