Switch case in C# - a constant value is expected

前端 未结 7 1010
太阳男子
太阳男子 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 05:54

    You can't use a switch statement for this as the case values cannot be evaluated expressions. For this you have to use an an if/else ...

    public static void Output(IEnumerable dataSource) where T : class
    {   
        dataSourceName = (typeof(T).Name);
        if(string.Compare(dataSourceName, typeof(CustomerDetails).Name.ToString(), true)==0)
        {
            var t = 123;
        }
        else if (/*case 2 conditional*/)
        {
            //blah
        }
        else
        {
            //default case
            Console.WriteLine("Test");
        }
    }
    

    I also took the liberty of tidying up your conditional statement. There is no need to cast to string after calling ToString(). This will always return a string anyway. When comparing strings for equality, bare in mind that using the == operator will result in a case sensitive comparison. Better to use string compare = 0 with the last argument to set case sensitive on/off.

提交回复
热议问题