C# 字符串类型上的类型切换
我有一个将字符串化数据解析为本机数据类型(自身属性)的类。它遍历类属性并使用与属性类型匹配的switch语句:C# 字符串类型上的类型切换,c#,C#,我有一个将字符串化数据解析为本机数据类型(自身属性)的类。它遍历类属性并使用与属性类型匹配的switch语句: using System.Reflection; … class DataParser { public int i { get; set; } public bool b { get; set; } public string s { get; set; } public DateTime d { get; set; } public De
using System.Reflection;
…
class DataParser
{
public int i { get; set; }
public bool b { get; set; }
public string s { get; set; }
public DateTime d { get; set; }
public Decimal e { get; set; }
public DataParser()
{
PropertyInfo[] properties = this.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
object currentValue = property.GetValue(this);
switch (currentValue)
{
case Int32 _:
…
break;
case DateTime _:
…
break;
case Decimal _:
…
break;
case Boolean _:
…
break;
case string _:
…
break;
default:
throw new Exception($"Could not find type for {property.PropertyType}");
}
}
}
}
类型匹配适用于所有类型,但字符串
除外,该字符串将抛出:
异常:找不到系统的类型。字符串
可能它不匹配,因为string
是引用类型?我用string
大小写替换了string
和System.string
,结果相同
更新
正如一些人所建议的,string属性的值是null
。设置默认值
公共字符串s{get;set;}=”“代码>
导致它匹配。我强烈怀疑这是因为该值为null。空值与类型模式不匹配。请尝试case-typeof(string):
而不是case-string:
您可能应该打开属性。PropertyType
,而不是值的具体类型(正如Jon指出的,它可能不存在)。@Romain否,OP没有打开类型,他们正在使用C#的新模式匹配语法打开一个值。您也可以使用枚举作为case-TypeCode.String: