Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在系统上切换表达式。键入C#8_C#_Switch Statement_C# 8.0 - Fatal编程技术网

在系统上切换表达式。键入C#8

在系统上切换表达式。键入C#8,c#,switch-statement,c#-8.0,C#,Switch Statement,C# 8.0,我很好奇,是否有其他方法可以用C#8中的新开关表达式编写类似这样的内容 公共静态对象转换(字符串str,类型)=> 类型开关 { _当type==typeof(string)=>str时, _当type==typeof(string[])=>str.Split(new[]{',',';'})时, _=>TypeDescriptor.GetConverter(类型).ConvertFromString(str) }; 因为\uuwhen type==typeof(string)看起来有点奇怪,尤

我很好奇,是否有其他方法可以用C#8中的新开关表达式编写类似这样的内容

公共静态对象转换(字符串str,类型)=>
类型开关
{
_当type==typeof(string)=>str时,
_当type==typeof(string[])=>str.Split(new[]{',',';'})时,
_=>TypeDescriptor.GetConverter(类型).ConvertFromString(str)
};

因为
\uuwhen type==typeof(string)
看起来有点奇怪,尤其是当我们有和其他非常方便的工具时。

正如其他人所提到的,您实际上需要一个类型的实例来使用新的类型匹配功能,而不是典型的
系统。type
。如果你想在类型上直接匹配,你现在的方式似乎是目前唯一可行的方式

话虽如此,我认为在这种情况下,标准的
switch
语句可能更具可读性:

switch (type)
{
    case Type _ when type == typeof(string):
        return str;

    case Type _ when type == typeof(string[]):
        return str.Split(',', ';');

    default:
        return TypeDescriptor.GetConverter(type).ConvertFromString(str);
}
如果确实希望保留开关表达式,则可以通过匹配类型名称来解决此问题:

public static object Convert(string str, Type type) =>
    type.Name switch
    {
        nameof(string) => str,
        nameof(string[]) => str.Split(new[] { ',', ';' }),
        _ => TypeDescriptor.GetConverter(type).ConvertFromString(str)
    };

不,恐怕只有这样了。是否可以将typeof移动到一个静态变量?允许像
\uuType==stringType=>str、
这样的东西,读起来可能会稍微好一点?您是否考虑过使用泛型而不是返回
对象
?不幸的是,泛型方法不适合我的情况这看起来确实像一个特殊的方法,也许这是一个XY问题,可以用一种完全不同但更好的方法来解决。值得注意的是,当您使用可为空的字段时,打开type.name会崩溃。e、 约会时间?将为“可空”