简体   繁体   中英

Using Switch case with Equals method in C#

Is there a way to convert the below if else condition into Switch in C#. I am using Equals method for checking the type, but unable to convert to switch case.

if (fi.FieldType.Equals(typeof(int)))
{
    fi.SetValue(data, BitConverter.ToInt32(buffer, 0));
}
else if (fi.FieldType.Equals(typeof(bool)))
{
    fi.SetValue(data, BitConverter.ToBoolean(buffer, 0));
}
else if (fi.FieldType.Equals(typeof(string)))
{
    byte[] tmp = new byte[la.length];
    Array.Copy(buffer, tmp, tmp.Length);
    fi.SetValue(data, System.Text.Encoding.UTF8.GetString(tmp));
}
else if (fi.FieldType.Equals(typeof(double)))
{
    fi.SetValue(data, BitConverter.ToDouble(buffer, 0));
}
else if (fi.FieldType.Equals(typeof(short)))
{
    fi.SetValue(data, BitConverter.ToInt16(buffer, 0));
}

Please help us....

With C# 7 pattern matching you can do this:

switch (fi.FieldType)
{
    case var _ when fi.FieldType.Equals(typeof(int)):
        fi.SetValue(data, BitConverter.ToInt32(buffer, 0));
        break;
    case var _ when fi.FieldType.Equals(typeof(bool)):
        fi.SetValue(data, BitConverter.ToBoolean(buffer, 0));
        break;

    //etc
}

Note that this is using _ to discard the value as we don't care about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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