Switch case in C# - a constant value is expected

前端 未结 7 1008
太阳男子
太阳男子 2020-11-27 05:50

My code is as follows:

public static void Output(IEnumerable dataSource) where T : class
{   
    dataSourceName = (typeof(T).Name);
    sw         


        
7条回答
  •  遥遥无期
    2020-11-27 06:05

    Now you can use nameof:

    public static void Output(IEnumerable dataSource) where T : class
    {
        string dataSourceName = typeof(T).Name;
        switch (dataSourceName)
        {
            case nameof(CustomerDetails):
                var t = 123;
                break;
            default:
                Console.WriteLine("Test");
        }
    }
    

    nameof(CustomerDetails) is basically identical to the string literal "CustomerDetails", but with a compile-time check that it refers to some symbol (to prevent a typo).

    nameof appeared in C# 6.0, so after this question was asked.

提交回复
热议问题