根据通用参数类型切换 [英] Switch based on generic argument type

查看:60
本文介绍了根据通用参数类型切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In C# 7.1 the below is valid code:

object o = new object();
switch (o)
{
    case CustomerRequestBase c:
        //do something
        break;
}

但是,我想在以下情况下使用模式切换语句:

However, I want to use the pattern switch statement in the following scenario:

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

IDE给我错误'T'是类型,在给定上下文中无效" 是否有一种优雅的方式来打开通用参数的类型?我在第一个示例中得到的结果是打开对象,第二个示例中要打开类型T.这样做的最佳方法是什么?

The IDE gives me the error "'T' is a type, which is not valid in the given context" Is there an elegant way to switch on the type of a generic parameter? I get that in my first example you are switching on the object and the second I'd want to switch on the type T. What would be the best approach to do this?

推荐答案

以下是两个不同的类,分别称为 Foo Bar .您可以将任何这些类的一个实例用作名为 Process 的函数的参数.毕竟,您可以执行示例功能中所示的模式匹配.该用法示例有一个名为 Test 的函数.

Below are two different classes called Foo and Bar. You can use one instance of any of these classes as a parameter to a function named Process. After all, you can perform pattern matching as shown in the example function. There is a function named Test for the usage example..

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 });
    }
}

这篇关于根据通用参数类型切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆