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");
}