首页 > 解决方案 > 从 String 转换为存储在 Type 变量中的类型

问题描述

我正在尝试做一种调试控制台,Unity以便能够更改 - 例如 -boolean在运行时启用/禁用值。

有一点我想在某个变量中设置一个值,但是该值存储为string(来自用户的输入),我需要将其转换为该变量的类型(存储在Type变量中),但我不知道这是否可能。

这是我遇到问题的代码部分:

private void SetValueInVariable(string variable, Type type, string toSet)
{
    //reflection - https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection
    Type container = typeof(StaticDataContainer);
    FieldInfo placeToSet = container.GetField(variable, BindingFlags.Static);
    placeToSet.SetValue(null, //here I need to convert "toSet"); 
}

我想知道这是否可能以及我该怎么做。

标签: c#type-conversion

解决方案


TypeDescriptor提供了一种相当健壮的方法来将字符串转换为特定类型。当然,这只适用于解析相当简单的少数类型。

private void SetValueInVariable(string variable, Type type, string toSet)
{
    //reflection - https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection
    Type container = typeof(StaticDataContainer);
    FieldInfo placeToSet = container.GetField(variable, BindingFlags.Static);
    var value = TypeDescriptor.GetConverter(type).ConvertFrom(toSet);
    placeToSet.SetValue(null, value); 
}

推荐阅读