简体   繁体   English

C# 8 开关表达式

[英]C# 8 Switch Expression

Can I replace this code snippent with a C#8 switch expression ?我可以用 C#8 switch expression替换此代码片段吗?

Note that if ObjectType is Computer, ObjectClass will contain "person" so ordering matters.请注意,如果 ObjectType 是 Computer,ObjectClass 将包含“person”,因此排序很重要。

Also, the question is academic and I am only interested in the switch expression and not how to solve this particular problem.此外,这个问题是学术性的,我只对switch expression感兴趣,而不是如何解决这个特定问题。

public List<string> ObjectClass { get; set; }
public ObjectType ObjectType {
    get {
        if (ObjectClass.Contains("group"))      { return ObjectType.Group; }
        if (ObjectClass.Contains("computer"))   { return ObjectType.Computer; }
        if (ObjectClass.Contains("person"))     { return ObjectType.User; }
        return ObjectType.Unknown;
    }
}

This answer builds off the solution provided by @IliarTurdushev and credit should go to him.这个答案建立在@IliarTurdushev 提供的解决方案的基础上,应该归功于他。 Also refactored using suggestion from @NetMage, with thanks.还使用@NetMage 的建议进行了重构,谢谢。

public class Program
{
    public  List<string> ObjectClass { get; set; }
    public  ObjectType sample
    {
        get => ObjectClass switch {
            _ when ObjectClass.Contains("group") => ObjectType.Group,
            _ when ObjectClass.Contains("computer") => ObjectType.Computer,
            _ when ObjectClass.Contains("person") => ObjectType.Person,
            _ => ObjectType.Unknown};
    }

    public enum ObjectType
    {
        Group = 1,
        Computer = 2,
        Person = 3,
        Unknown = 4
    }
}

You could combine LINQ and switch to have a (semi) efficient version:您可以结合 LINQ 和switch来获得(半)高效版本:

public ObjectType type
{
    get => ObjectClass.Select(c => c switch { "group" => ObjectType.Group, "computer" => ObjectType.Computer, "person" => ObjectType.Person, _ => (ObjectType?)null})
                      .FirstOrDefault(t => t != null) ?? ObjectType.Unknown;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM