C# 字符串类型上的类型切换

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

我有一个将字符串化数据解析为本机数据类型(自身属性)的类。它遍历类属性并使用与属性类型匹配的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 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: