基于泛型参数类型的切换

Dav*_*lds 9 c# generics pattern-matching switch-statement c#-7.1

在 C# 7.1 中,以下是有效代码:

object o = new object();
switch (o)
{
    case CustomerRequestBase c:
        //do something
        break;
}
Run Code Online (Sandbox Code Playgroud)

但是,我想在以下场景中使用模式 switch 语句:

public T Process<T>(object message, IMessageFormatter messageFormatter) 
    where T : class, IStandardMessageModel, new()
{
    switch (T)
    {
        case CustomerRequestBase c:
            //do something
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

IDE 给我错误“'T' 是一种类型,在给定的上下文中无效”有没有一种优雅的方法来切换泛型参数的类型?我知道在我的第一个例子中你正在打开对象,第二个我想打开类型 T。这样做的最佳方法是什么?

Abd*_*len 11

下面是两个不同的类,称为FooBar。您可以使用任何这些类的一个实例作为名为Process的函数的参数。毕竟,您可以执行示例函数中所示的模式匹配。使用示例中有一个名为Test的函数。

public class Foo
{
    public string FooMsg { get; set; }
}

public class Bar
{
    public string BarMsg { get; set; }
}

public class Example
{
    public T Process<T>(T procClass) where T : class
    {
        switch (typeof(T))
        {
            case
                var cls when cls == typeof(Foo):
                {
                    var temp = (Foo)((object)procClass);
                    temp.FooMsg = "This is a Foo!";

                    break;
                }

            case
                var cls when cls == typeof(Bar):
                {
                    var temp = (Bar)((object)procClass);
                    temp.BarMsg = "This is a Bar!";

                    break;
                }
        }

        return
            procClass;
    }

    public void Test(string message)
    {
        Process(new Foo() { FooMsg = message });
        Process(new Bar() { BarMsg = message });
    }
}
Run Code Online (Sandbox Code Playgroud)


Mos*_*ini 7

我同意在某些情况下这种方法更快而且不那么难看,并且也同意在任何情况下都应该找到更好的解决方案,但有时这种权衡并不值得……所以这里是一个解决方案(C# 9.0)

return typeof(T) switch
{
    Type t when t == typeof(CustomerRequestBase) => /*do something*/ ,
    _ => throw new Exception("Nothing to do")
};
Run Code Online (Sandbox Code Playgroud)