C#中如何将字符串形式的数值类型名(如"sbyte")转换为对应类型?
Hey there! Let's tackle your two C# questions together—they're closely linked, so we can solve them in a way that cleans up your code and addresses the type conversion issue.
1. Converting string type names to actual numeric types
First, to turn a string like "sbyte" into its corresponding System.SByte type, we need to handle C#'s type aliases (since C# uses shorthand names for many system types). Here's a helper method that maps common numeric type aliases to their full system type names, then retrieves the Type object:
using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using static System.Console; namespace Exercise02 { class Program { private static Type GetNumericType(string typeName) { // Map C# type aliases to their full System type names var typeAliasMap = new Dictionary<string, string> { { "sbyte", "System.SByte" }, { "byte", "System.Byte" }, { "short", "System.Int16" }, { "ushort", "System.UInt16" }, { "int", "System.Int32" }, { "uint", "System.UInt32" }, { "long", "System.Int64" }, { "ulong", "System.UInt64" }, { "float", "System.Single" }, { "double", "System.Double" }, { "decimal", "System.Decimal" } }; // Check if we have an alias, otherwise try the input directly if (typeAliasMap.TryGetValue(typeName.ToLower(), out var systemTypeName)) { return Type.GetType(systemTypeName, true, true); // Throw if type not found } return Type.GetType(typeName, true, true); }
2. Encapsulating your WriteLine logic into reusable methods
Next, let's clean up all those repeated WriteLine calls by moving the output logic into dedicated methods. We'll also use reflection to fetch the MinValue and MaxValue for each numeric type (since those are static fields on each type):
// Helper to get static field values (like MinValue/MaxValue) private static object GetStaticFieldValue(Type type, string fieldName) { var field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.Static); return field?.GetValue(null); // Static fields don't need an instance, pass null } private static void PrintHeader() { var format = "{0,-10} | {1,-4} | {2,30} | {3,30} |"; WriteLine(string.Format(format, "Type", "Size", "Min", "Max")); } private static void PrintTypeInfo(string typeName) { var format = "{0,-10} | {1,-4} | {2,30} | {3,30} |"; var type = GetNumericType(typeName); // Get size of the type in bytes var size = Marshal.SizeOf(type); // Get Min/Max values via reflection var minValue = GetStaticFieldValue(type, "MinValue"); var maxValue = GetStaticFieldValue(type, "MaxValue"); WriteLine(string.Format(format, type.Name, size, minValue, maxValue)); } private static void HorizontalLine() { // Replace with your existing horizontal line logic WriteLine(new string('-', 80)); }
Updated Main Method
Now your Main method becomes clean and focused, no more repeated WriteLine calls:
static void Main(string[] args) { // List of numeric type names you want to display var numericTypes = new List<string> { "sbyte", "byte", "short", "ushort", "int", "uint", "long", "ulong", "float", "double", "decimal" }; HorizontalLine(); PrintHeader(); HorizontalLine(); foreach (var typeName in numericTypes) { PrintTypeInfo(typeName); } HorizontalLine(); } } }
Key Notes
- Type Conversion: The
GetNumericTypemethod handles the alias-to-type conversion, so you can pass shorthand names like"sbyte"and get the correctTypeobject. - Reusability: By moving output logic into
PrintHeaderandPrintTypeInfo, you can easily modify the format or add new types without duplicating code. - Reflection: We use reflection to fetch
MinValueandMaxValuebecause these properties are specific to each numeric type—this avoids writing separate logic for every type.
内容的提问来源于stack exchange,提问作者Valdas Stonkus

