gpt4 book ai didi

c# - 在 C# 2.0 中使用 Invoke 调用时,参数从 null 转换为 DateTime.MinValue

转载 作者:太空狗 更新时间:2023-10-30 00:36:27 26 4
gpt4 key购买 nike

我的代码有点像这样

public class MyObject
{
private bool IsValidDay(ref DateTime theDate)
{

...
}
}


MethodInfo[] methods = myObjectInstance.GetType().GetMethod("IsValidDay", BindingFlags.Instance | BindingFlags.NonPublic);
object[] args = { null };
bool val = (bool)method.Invoke(myObjectInstance, args);

但是当从 IsValidDay 方法中调用该方法时,theDate 是 DateTime.MinValue。这看起来非常奇怪 - 我可能希望抛出 NullReferenceException 而不是自动转换。

如果您想知道,这是单元测试中的代码。 (在使用中,该方法通常通过采用对象的公共(public)方法调用)。

就后续调用的一些其他代码而言,DateTime.MinValue 和 null 不是一回事,所以有点问题。

有什么线索吗?建议。

最佳答案

来自 MSDN :

Any object in this array that is not explicitly initialized with a value will contain the default value for that object type. For reference-type elements, this value is null. For value-type elements, this value is 0, 0.0, or false, depending on the specific element type.

DateTime 的默认值为DateTime.MinValue:

DateTime.MinValue == new DateTime() // true

这解释了为什么当您使用 null 调用方法时,DateTime.MinValue 会被传递给该方法。

请注意,当您在没有反射的情况下调用它时,您无论如何都不能将 null 传递给该方法:

DateTime dt = null; // cannot assign null to value type
obj.IsValidDay(ref dt);

所以我会说您不需要使用空引用来测试您的方法。


如果您希望您的方法接受null,您可以将声明更改为DateTime?,正如其他人已经指出的那样:

private bool IsValidDay(ref DateTime? dt) { ... }

关于c# - 在 C# 2.0 中使用 Invoke 调用时,参数从 null 转换为 DateTime.MinValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1889749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com