C# 从字符串转换为类型变量中存储的类型
我试图在C# 从字符串转换为类型变量中存储的类型,c#,type-conversion,C#,Type Conversion,我试图在Unity中执行一种调试控制台,以便能够在运行时更改(例如,启用/禁用boolean值) 有一个点,我想在某个变量中设置一个值,但该值存储为字符串(用户输入),我需要将其转换为该变量的类型(存储在类型变量中),但我不知道这是否可行 这是我的代码中存在问题的部分: private void SetValueInVariable(string variable, Type type, string toSet) { //reflection - https://docs.micros
Unity
中执行一种调试控制台,以便能够在运行时更改(例如,启用/禁用boolean
值)
有一个点,我想在某个变量中设置一个值,但该值存储为字符串(用户输入),我需要将其转换为该变量的类型(存储在类型变量中),但我不知道这是否可行
这是我的代码中存在问题的部分:
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");
}
我想知道这是否可行,以及如何实现。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);
}
不要将变量命名为var
@maccettura…或value
,因为:-)@dasblinkenlight错过了那一个!编辑。感谢you@StriplingWarrior对不起,我弄错了哦,谢谢!我只是想把它转换成标准类型,所以我想它可以工作。