为什么 dynamic 在第一种情况下有效而在第二种情况下无效?
Why does dynamic work in the first case but not in the second?
这就过去了
var badRequestObjectResult = new BadRequestObjectResult(new { ErrorMessage = "Hi" });
dynamic response = badRequestObjectResult.Value;
Assert.Equal("Hi", response.ErrorMessage);
虽然失败了
dynamic response2 = ((BadRequestObjectResult)result).Value;//result is an IActionResult
Assert.Equal("Hi", response2.ErrorMessage);
"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : 'object' does not contain a definition for 'ErrorMessage'"
您需要扩展您的答案以包含一个完整且可重现的示例。您所描述的内容按预期工作而没有错误,因此必须有一些介于两者之间的东西导致问题,例如自定义克隆或序列化正在改变 ObjectResult 的值背后的识别类型。
[Test]
public void TestDynamic()
{
var response1 = new BadRequestObjectResult(new { Message = "Hi." });
var response2 = buildResponse();
dynamic value1 = response1.Value;
dynamic value2 = ((BadRequestObjectResult)response2).Value;
string message1 = value1.Message;
string message2 = value2.Message;
Assert.AreEqual(message1, message2);
}
private IActionResult buildResponse()
{
return new BadRequestObjectResult(new { Message = "Hi." });
}
我重现错误的唯一方法是如果 buildResponse 返回:
return new BadRequestObjectResult(new object());
返回任何缺少消息的匿名类型或其他 class 属性 会导致反映基础类型的消息。
这就过去了
var badRequestObjectResult = new BadRequestObjectResult(new { ErrorMessage = "Hi" });
dynamic response = badRequestObjectResult.Value;
Assert.Equal("Hi", response.ErrorMessage);
虽然失败了
dynamic response2 = ((BadRequestObjectResult)result).Value;//result is an IActionResult
Assert.Equal("Hi", response2.ErrorMessage);
"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : 'object' does not contain a definition for 'ErrorMessage'"
您需要扩展您的答案以包含一个完整且可重现的示例。您所描述的内容按预期工作而没有错误,因此必须有一些介于两者之间的东西导致问题,例如自定义克隆或序列化正在改变 ObjectResult 的值背后的识别类型。
[Test]
public void TestDynamic()
{
var response1 = new BadRequestObjectResult(new { Message = "Hi." });
var response2 = buildResponse();
dynamic value1 = response1.Value;
dynamic value2 = ((BadRequestObjectResult)response2).Value;
string message1 = value1.Message;
string message2 = value2.Message;
Assert.AreEqual(message1, message2);
}
private IActionResult buildResponse()
{
return new BadRequestObjectResult(new { Message = "Hi." });
}
我重现错误的唯一方法是如果 buildResponse 返回:
return new BadRequestObjectResult(new object());
返回任何缺少消息的匿名类型或其他 class 属性 会导致反映基础类型的消息。