C# 将字符串转换为对象类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16973465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string to type in object
提问by griegs
The code I have to implement takes a posted list of data from an Ajax call from a web page.
我必须实现的代码从网页的 Ajax 调用中获取已发布的数据列表。
I know the object I need to update, but each field/value pair is coming through as string values and not as their proper types.
我知道我需要更新的对象,但每个字段/值对都是作为字符串值而不是它们的正确类型出现的。
So I am trying to work out the type of the property, casting the value as the new type and then apply that to the field using reflection.
所以我试图找出属性的类型,将值转换为新类型,然后使用反射将其应用于字段。
However I am getting the following error for anything other than strings.
但是,对于字符串以外的任何内容,我都收到以下错误。
Invalid cast from 'System.String' to 'System.TimeSpan'.
The code I am attempting the conversion in is;
我尝试转换的代码是;
public void Update<T>(string fieldName, string fieldValue)
{
System.Reflection.PropertyInfo propertyInfo = typeof(T).GetProperty(fieldName);
Type propertyType = propertyInfo.PropertyType;
var a = Convert.ChangeType(fieldValue, propertyType);
}
So is the target object.
目标对象也是如此。
采纳答案by Simon Mourier
There is no absolute answer that works for all types. But, you could use a TypeConverterinstead of Convert, it usually works better. For example, there is a TimeSpanConverter:
没有适用于所有类型的绝对答案。但是,您可以使用TypeConverter而不是 Convert,它通常效果更好。例如,有一个TimeSpanConverter:
public void Update<T>(string fieldName, string fieldValue)
{
System.Reflection.PropertyInfo propertyInfo = typeof(T).GetProperty(fieldName);
Type propertyType = propertyInfo.PropertyType;
TypeConverter converter = TypeDescriptor.GetConverter(type);
if (converter.CanConvertFrom(typeof(string)))
{
var a = converter.ConvertFrom(fieldValue, type);
...
}
}
回答by Mzf
In order to use Convertthe type need to be IConvertible
为了使用Convert类型需要IConvertible
From MSDN
来自MSDN
For the conversion to succeed, value must implement the IConvertible interface
For the conversion to succeed, value must implement the IConvertible interface
TimeSpandoesn't implement it ...
TimeSpan没有实现它......
So you can check before calling Convertor add try{} catch{}
所以你可以在打电话Convert或添加之前检查try{} catch{}
回答by Steve Andrews
For handling JSON in MVC (and .NET in general) I use JSON.NET. It is included out-of-the-box in the ASP.NET MVC 4 project template and available on NuGet otherwise. Deserializing JSON string content is (generally) as simple as:
为了在 MVC(以及一般的 .NET)中处理 JSON,我使用 JSON.NET。它包含在 ASP.NET MVC 4 项目模板中开箱即用,否则可在 NuGet 上使用。反序列化 JSON 字符串内容(通常)非常简单:
JsonConvert.DeserializeObject<Customer>(json);
If the JSON being passed isn't a serialized model, you could create a code model to match the JSON.
如果传递的 JSON 不是序列化模型,您可以创建一个代码模型来匹配 JSON。
If that doesn't work for your scenario, you can try the Convertclass which has options for conversion if you know the type:
如果这不适用于您的场景,您可以尝试使用Convert具有转换选项的类(如果您知道类型):
Convert.ToInt32(stringValue);
Or the ChangeTypemethod if it's dynamic:
或者ChangeType方法,如果它是动态的:
Convert.ChangeType(value, conversionType);

