【发布时间】:2018-09-10 13:32:16
【问题描述】:
我做了一个工作练习,但我的代码看起来不太好。我的代码中有很多WriteLine 语句,我想创建一个方法。但是如何将字符串“sbyte”转换为类型 sbyte 我不知道。
using System;
using static System.Console;
namespace Exercise02
{
class Program
{
static void Main(string[] args)
{
string strFormat = "{0,-10} | {1,-4} | {2,30} | {3,30} |";
HorizontalLIne();
WriteLine(String.Format(strFormat, "Type", "Size", "Min", "Max"));
HorizontalLIne();
// I would like to write a method of this block of code
WriteLine(String.Format(strFormat, "sbyte", sizeof(sbyte), sbyte.MinValue, sbyte.MaxValue));
WriteLine(String.Format(strFormat, "byte", sizeof(byte), byte.MinValue, byte.MaxValue));
WriteLine(String.Format(strFormat, "short", sizeof(short), short.MinValue, short.MaxValue));
WriteLine(String.Format(strFormat, "ushort", sizeof(ushort), ushort.MinValue, ushort.MaxValue));
WriteLine(String.Format(strFormat, "int", sizeof(int), int.MinValue, int.MaxValue));
WriteLine(String.Format(strFormat, "uint", sizeof(uint), uint.MinValue, uint.MaxValue));
WriteLine(String.Format(strFormat, "long", sizeof(long), long.MinValue, long.MaxValue));
WriteLine(String.Format(strFormat, "ulong", sizeof(ulong), ulong.MinValue, ulong.MaxValue));
WriteLine(String.Format(strFormat, "float", sizeof(float), float.MinValue, float.MaxValue));
WriteLine(String.Format(strFormat, "double", sizeof(double), double.MinValue, double.MaxValue));
WriteLine(String.Format(strFormat, "decimal", sizeof(decimal), decimal.MinValue, decimal.MaxValue));
HorizontalLIne();
}
private static void HorizontalLIne()
{
WriteLine("-------------------------------------------------------------------------------------");
}
}
}
我的计划是制作一个字符串列表,例如“sbyte”、“byte”、“int”……并编写一个方法。
我尝试了以下方法:
string type = "sbyte";
private static void WriteLineOfType(string strFormat, string type)
{
Type typeFromString = Type.GetType(type);
WriteLine(String.Format(strFormat,
type,
sizeof(typeFromString),
typeFromString.MinValue,
typeFromString.MaxValue));
}
但是这种方法行不通。
我如何编写获取字符串的正确方法,例如 sbyte 并写入控制台 sizeof(sbyte)、sbyte.MinValue、sbyte.MaxValue?
【问题讨论】: