简体   繁体   English

C#-具有自定义日期格式的类型转换器

[英]C# - type converter with custom date format

This is my code to check if the value can be converted to given type. 这是我的代码,用于检查该值是否可以转换为给定类型。

public static object TryParseObject<T>(object valueObject)
    {
        string value = null;

        try
        {
            value = Convert.ToString(valueObject);
            var converter = TypeDescriptor.GetConverter(typeof(T));

            if (converter != null)
            {
                //Cast ConvertFromString(string text) : object to (T)
                return (T)converter.ConvertFromString(value);
            }
            return default(T);
        }
        catch
        {
            //Can't parse
        }
    }

This works as it should be. 这可以正常工作。 Now I need to convert from date string to DateTime with custom format only (say for ex. format: "MM.DD.YYYY HH:mm:ss"). 现在,我只需要使用自定义格式将日期字符串转换为DateTime (例如,示例格式:“ MM.DD.YYYY HH:mm:ss”)。 How can I achieve that? 我该如何实现?

Should I handle the DateTime scenario separately? 我应该单独处理DateTime方案吗? like: 喜欢:

 if(typeof(T) == typeof(DateTime)) {...}
 else {...}

I'm looking to see if I can use the existing code with few changes. 我正在寻找是否可以通过少量更改使用现有代码。 Thanks. 谢谢。

If you change a method signature to the same as other TryParse.. methods 如果将方法签名更改为与其他TryParse..方法相同

public static bool TryParseObject<T>(object valueObject, out T outValue)
{
    //your parsing code
}

Then you can create overloads for any type you want. 然后,您可以为所需的任何类型创建重载。 With separated method your code stay clean and easy to understand 使用单独的方法,您的代码可以保持整洁并易于理解

public static bool TryParseObject(object valueObject, out DateTime outValue)
{
    const string EXACT_FORMAT = "MM.DD.YYYY HH:mm:ss";
    // your parsing to DateTime
}

public static bool TryParseObject(object valueObject, out int outValue)
{
    // your parsing to int
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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