You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 GetNumericType method handles the alias-to-type conversion, so you can pass shorthand names like "sbyte" and get the correct Type object.
  • Reusability: By moving output logic into PrintHeader and PrintTypeInfo, you can easily modify the format or add new types without duplicating code.
  • Reflection: We use reflection to fetch MinValue and MaxValue because these properties are specific to each numeric type—this avoids writing separate logic for every type.

内容的提问来源于stack exchange,提问作者Valdas Stonkus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:37:00