为什么 DateTime 的 GetType 不是常量值

Why the GetType of DateTime is not a constant value

我正在处理带有类型检查的 switch 语句。以下代码适用于所有类型,但挑战在于 Nullable 类型。

  switch (Type.GetTypeCode( propertyInfos.PropertyType))
                    {
                        // Type code doesn't have reference with int, long, etc.,
                        case TypeCode.DateTime:
                            // Do the work for DateTime
                            break;
                        case TypeCode.Int32 :
                            // Do the work for Int32
                            break;
                        case TypeCode.Int64:
                            // Do the work for long
                            break;
                        case TypeCode.DateTime? :
                            break;
                        default:
                            break;
                    }

我试过将其更改为 GetTypeDateTime.Today.GetType().ToString() 会给我们 System.DateTime 作为字符串。但是,当使用时,编译器会抛出错误,因为它不是有效的 Constant string。在任何给定的时间实例中,DateTime.Today.GetType() 总是会给我们 System.DateTime,为什么这不被编译器接受?

我用过Nullable.GetUnderlyingType方法。我对可为空的类型应用了类型检查,然后确定了可为空的类型,最后指定了可为空的泛型类型。

if (Nullable.GetUnderlyingType(propertyType) != null)
            {
                // It's nullable
                Console.WriteLine(propertyType.GetGenericArguments()[0]);

            }

我找到了 this clever solution using a dictionary instead of a switch。使用该方法,这应该适合您:

public class Test {
    public DateTime A { get; set; }
    public Int32 B { get; set; }
    public Int64 C { get; set; }
    public DateTime? D { get; set; }
}

...Main...
        var @switch = new Dictionary<Type, Action> {
            { typeof(DateTime), () => Console.WriteLine("DateTime") },
            { typeof(Int32), () => Console.WriteLine("Int32") },
            { typeof(Int64), () => Console.WriteLine("Int64") },
            { typeof(DateTime?), () => Console.WriteLine("DateTime?") },
        };

        foreach (var prop in typeof(Test).GetProperties()) {
            @switch[prop.PropertyType]();
        }