C# 从int的显式转换->;sbyte->;斯拜特?

C# 从int的显式转换->;sbyte->;斯拜特?,c#,C#,给定此代码段 [TestMethod] public void SByte() { int integerValue = -129; sbyte sbyteValueFromInt = (sbyte) integerValue; Assert.AreEqual(sbyteValueFromInt, 127); // True byte byteValue = (byte) integerValue; sbyte sbyteValueFromByte= (sbyte) byteValu

给定此代码段

[TestMethod]
public void SByte()
{
 int integerValue = -129;
 sbyte sbyteValueFromInt = (sbyte) integerValue;
 Assert.AreEqual(sbyteValueFromInt, 127); // True

 byte byteValue = (byte) integerValue;
 sbyte sbyteValueFromByte= (sbyte) byteValue;
 Assert.AreEqual(sbyteValueFromByte, 127); // True 

 sbyte? nullableSbyte = sbyteValueFromByte;
 Assert.AreEqual(nullableSbyte.Value, 127); // True
 Assert.AreEqual((sbyte)nullableSbyte, 127); // True
 Assert.AreEqual(nullableSbyte, 127); // Assert.AreEqual failed. Expected:<127 (System.SByte)>. Actual:<127 (System.Int32)>. 
}
为什么它不知道如何将
127
转换为
sbyte
,但它对
sbyte?

这似乎是MSTest的一个bug特性。当使用
NUnit
重复测试时,或仅使用
运算符==
时,隐式转换是有效的

Assert.AreEqual<object>(expected, actual, message, parameters);

public static void AreEqual<T>(T expected, T actual, string message, params object[] parameters)
{
 message = Assert.CreateCompleteMessage(message, parameters);
 if (object.Equals((object) expected, (object) actual))
  return;
 Assert.HandleFailure ...
}
MSTest的断言归结为:

Assert.AreEqual<object>(expected, actual, message, parameters);

public static void AreEqual<T>(T expected, T actual, string message, params object[] parameters)
{
  message = Assert.CreateCompleteMessage(message, parameters);
  if (object.Equals((object) expected, (object) actual))
    return;
  Assert.HandleFailure ...
}
然后就过去了

相比之下,NUnit断言在没有任何帮助的情况下通过:

    [Test]
    public void SByte()
    {
        sbyte? nullableSbyte = sbyteValueFromByte;
        Assert.AreEqual(nullableSbyte.Value, 127); // True
        Assert.AreEqual(nullableSbyte, 127);
    }
就像穷人的单元测试一样:

    sbyte? nullableSbyte = sbyteValueFromByte;
    if (nullableSbyte.Value != 127)
    {
        throw new Exception("Not Equal");
    }
    if (nullableSbyte != 127)
    {
        throw new Exception("Not Equal");
    }
编辑


@sudhakardipudi
nullableSbyte.Value
sbyte
nullableSbyte
是否为
sbyte?
。如果
对象
是罪魁祸首,通过
装箱
拆箱
,它不应该尊重C规范中的
显式nullable转换
从S到T的显式转换?
我用R#粘贴了一个屏幕截图-似乎只有在127在装箱之前转换为
sbyte
时,装箱比较才是真的。如果我这样做
Assert.AreEqual((object)nullableSbyte.Value,(object)127)
,R#也表示
类型转换是冗余的
。如果我们深入研究
AreEqual
,那么它不应该识别
127
转换为
sbyte
?为什么它不知道如何将
127
转换为
sbyte?
但它对
sbyte
进行了转换?这就是为什么
MSTest
在这里不起作用的原因-它让
对象来决定。等于
来比较两个装箱值(
sbyte
int
),这失败了(可能涉及到类型检查?)。MSTest需要在仅仅使用
object.Equals
之前做更多的基础工作,例如,在执行空检查并确定是否存在隐式转换之后取消绑定这两个对象,等等。
    sbyte? nullableSbyte = sbyteValueFromByte;
    if (nullableSbyte.Value != 127)
    {
        throw new Exception("Not Equal");
    }
    if (nullableSbyte != 127)
    {
        throw new Exception("Not Equal");
    }