Eug*_*ene 2 c# switch-statement unreachable-code
我正在实现一些通用IEqualityComparer<T> Equal()方法,当交换机中的代码无法访问时,我没有明显的理由:
public bool Equals(T x, T y)
{
switch (nameof(T))
{
case nameof(Accessory):
return (x as Accessory).Id == (y as Accessory).Id;//not reachable
default:
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
有人有线索吗?
nameof评估的名字T在编译的时候,所以这是一个常量字符串,"T"以及因此只有default情况下都不会服用.
这是一个替代实现:
public bool Equals(T x, T y)
{
if (x is Accessory && y is Accessory)
{
var ax = x as Accessory;
var ay = y as Accessory;
return ax.Id == ay.Id;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
C#7.1介绍了一些语法糖:
public bool Equals(T x, T y)
{
if (x is Accessory ax && y is Accessory ay)
{
return ax.Id == ay.Id;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
(请注意,false如果x和y都是null,则摘录会返回;我的版本中没有修复此问题.)
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |