【发布时间】:2016-03-23 08:44:13
【问题描述】:
我有以下代码,用作说明不同场景的示例:
public static void MethodWithOptionalGuid(Guid id = default(Guid)) { }
public static void MethodWithOptionalInteger(int id = 2) { }
public static void MethodWithOptionalString(string id = "33344aaa") { }
public static void MethodWithoutOptionalParameter(int id, Guid longId) { }
static void Main(string[] args)
{
var methods = typeof(Program).GetMethods(BindingFlags.Public | BindingFlags.Static).ToList();
foreach (var method in methods)
{
PrintMethodDetails(method);
}
Console.ReadLine();
}
static void PrintMethodDetails(MethodInfo method)
{
Console.WriteLine(method.Name);
foreach (var parameter in method.GetParameters().ToList())
{
Console.WriteLine(parameter.Name +
" of type " + parameter.ParameterType.ToString() +
" with default value:" + parameter.DefaultValue);
}
Console.WriteLine();
}
它打印以下内容:
MethodWithOptionalGuid
id of type System.Guid with default value:
MethodWithOptionalInteger
id of type System.Int32 with default value:2
MethodWithOptionalString
id of type System.String with default value:33344aaa
MethodWithoutOptionalParameter
id of type System.Int32 with default value:
longId of type System.Guid with default value:
最后 3 种方法的输出似乎很好。
我的问题是关于第一个 MethodWithOptionalGuid:为什么无法识别 Guid 的默认值?
我希望收到类似 "0000000-..." 的信息。我还尝试使用 new Guid() 和相同的结果初始化可选参数。我也尝试了其他结构,例如 TimeSpan 并且行为是相同的。
我希望所有值类型的行为都相同(如整数示例所示)。
额外:我在 Asp.Net MVC 中尝试使用带有可选 Guid 参数的操作时发现了这个问题,但失败了(必须使 Guid 可以为空)。浏览 MVC 代码,发现它在某些时候使用了 DefaultValue。所以我制作了这个代码示例来更好地说明我的问题。
【问题讨论】:
-
@vc74 我更新了我的问题。虽然我同意最后 3 种方法的输出符合我的预期,但我无法理解第一种方法的输出。
-
我认为OP的问题主要是关于
MethodWithOptionalGuid。指定了一个默认值,我也想知道为什么default(Guid)不会导致“0000..” -
@RaphaëlAlthaus 它还说默认(Guid)| new Guid() 是编译器已知的值,它应该可以工作。根本原因解释了为什么您不能使用 Guid.Empty。
-
@RaphaëlAlthaus 我不明白:代码编译得很好,如果你在
MethodWithOptionalGuid中输出id的值,它 is "00000-".. . 那么为什么parameter.DefaultValue是null而不是Guid.Emtpy?
标签: c# reflection optional-parameters value-type base-class-library