【问题标题】:Why the GetType of DateTime is not a constant value为什么 DateTime 的 GetType 不是常数值
【发布时间】:2017-11-29 04:39:35
【问题描述】:

我正在处理带有类型检查的 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,为什么编译器不接受?

【问题讨论】:

  • 你有两次 DateTime。第一种情况和最后一种非默认情况都是 DateTime。消息是“switch 语句包含标签值为 '16' 的多个案例”。投票结束。

标签: c# oop c#-4.0 switch-statement c#-3.0


【解决方案1】:

我找到了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]();
        }

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-06-13
      • 2014-07-23
      • 2011-10-19
      • 2021-01-06
      • 2010-10-05
      • 1970-01-01
      • 2011-12-22
      • 2013-05-19
      相关资源
      最近更新 更多