可以使用以下代码实现将字符串转换为指定泛型类型:

public static T ConvertStringToType<T>(string value)
{
    Type type = typeof(T);

    if (type == typeof(int))
    {
        int result;
        if (int.TryParse(value, out result))
        {
            return (T)Convert.ChangeType(result, type);
        }
    }
    else if (type == typeof(double))
    {
        double result;
        if (double.TryParse(value, out result))
        {
            return (T)Convert.ChangeType(result, type);
        }
    }
    // 添加其他类型的转换

    return default(T);
}

使用示例:

string str = '123';
int intValue = ConvertStringToType<int>(str); // intValue = 123

string doubleStr = '3.14';
double doubleValue = ConvertStringToType<double>(doubleStr); // doubleValue = 3.14

如果需要将字符串转换为数字类型,可以使用以下代码:

public static T ConvertStringToNumber<T>(string value) where T : struct, IConvertible
{
    Type type = typeof(T);

    if (type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(byte))
    {
        long result;
        if (long.TryParse(value, out result))
        {
            return (T)Convert.ChangeType(result, type);
        }
    }
    else if (type == typeof(double) || type == typeof(float) || type == typeof(decimal))
    {
        decimal result;
        if (decimal.TryParse(value, out result))
        {
            return (T)Convert.ChangeType(result, type);
        }
    }
    // 添加其他数字类型的转换

    return default(T);
}

使用示例:

string str = '123';
int intValue = ConvertStringToNumber<int>(str); // intValue = 123

string doubleStr = '3.14';
double doubleValue = ConvertStringToNumber<double>(doubleStr); // doubleValue = 3.14
C# WPF: 使用泛型和反射将字符串转换为指定类型

原文地址: https://www.cveoy.top/t/topic/kgFF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录