如何在C#中将Type转换为Int、float、bool或char结构



我正在用java实现一个代码生成器,它将创建一个C#代码。当我需要使用Console时。ReadLine((变量有一个类型,但我在生成代码时不知道类型。

那么,是否可以从Console转换类型。只使用变量ReadLine((?

代码示例:

public static void main()
{
var a = 1;
var b = 2;
/* The variable 'a' has a value and is of type integer, 
* but when I generate this code I don't have this information */
a = Console.ReadLine();

/*I've tried to get type of variable but I didn't get success */
var type = a.GetType();
a = type.Parse(Console.ReadLine());
}

像这样的通用解析器怎么样,它会查看字符串并尝试查看它是否与您列出的类型之一匹配。如果匹配,它会返回值和一个Type(这样你就可以尝试弄清楚你得到了什么(。

public static (object value, Type type) ConvertToAnything(string input)
{
if (int.TryParse(input, out var intResult))
{
return (intResult, typeof(int));
}
if (double.TryParse(input, out var doubleResult))
{
return (doubleResult, typeof(double));
}
if (input.Length == 1)
{
return (input[0], typeof(char));
}
if (input.Equals("true", StringComparison.InvariantCultureIgnoreCase))
{
return (true, typeof(bool));
}
if (input.Equals("false", StringComparison.InvariantCultureIgnoreCase))
{
return (false, typeof(bool));
}
return (input, typeof(string));
}

(object value, Type type)返回类型表示该方法返回一个元组,该元组将intType配对。

下面是一些测试代码,看看它是否有效:

var (result, type) = UniversalConverter.ConvertToAnything("123.4");
(result, type) = UniversalConverter.ConvertToAnything("false");
(result, type) = UniversalConverter.ConvertToAnything("123");
(result, type) = UniversalConverter.ConvertToAnything("a");

使用此函数SetVariableValueFromInput,我能够将字符串转换为引用对象的类型。

public static void @main()
{
var a = 1;
var b = 2;
SetVariableValueFromInput(ref a, Console.ReadLine());
}
static void SetVariableValueFromInput<T>(ref T myVariable, string myImput)
{
var converter = TypeDescriptor.GetConverter(typeof(T));
myVariable = (T)(converter.ConvertFromInvariantString(myImput));
}

由于已将值1分配给var a,因此它是整数类型。现在,在从控制台读取值时,您必须将其转换为int.

public static void main()
{
var a = 1;
var b = 2;
/* The variable 'a' has a value and is of type integer, 
* but when I generate this code I don't have this information */
a = Convert.ToInt32(Console.ReadLine());
}

最新更新