简体   繁体   中英

Why the GetType of DateTime is not a constant value

I'm working on a switch statement with Type checking. The following code is working perfectly well for all the types, but, the challenge is with Nullable types.

  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;
                    }

I have tried that to change as GetType and DateTime.Today.GetType().ToString() would give us System.DateTime as a string. But, when used the compiler throws error as that is not a valid Constant string . At any given time instance, DateTime.Today.GetType() would always gives us System.DateTime , why this is not accepted by compiler?

I found this clever solution using a dictionary instead of a switch . Using that method, this should work for you:

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]();
        }

I have used Nullable.GetUnderlyingType Method. I have applied type checking for nullable type then identified the nullable type and then finally specified the nullable's generic type.

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

            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM