csharp GenericStringParserExtensionMethod.cs

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp GenericStringParserExtensionMethod.cs相关的知识,希望对你有一定的参考价值。

/*
C# Generic String Parser Extension Method
Code Snippet By: Pinal Bhatt [www.PBDesk.com]
http://blogs.pbdesk.com/c-generic-string-parser-extension-method/
Working Example at http://ideone.com/ZP5xo
Usage:
string s = "32";
int i = s.As<int>();
*/

using System.ComponentModel;
using System;
public static class StringExtensions
    {        
        public static T As<T>(this string strValue, T defaultValue)
        {
            T output = defaultValue;
            if (output == null)
            {
                output = default(T);
            }
            TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
            if (converter != null)
            {
                try
                {
                    output = (T)converter.ConvertFromString(strValue);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            return output;
        }

        public static T As<T>(this string strValue)
        {
            return strValue.As<T>(default(T));
        }
}

以上是关于csharp GenericStringParserExtensionMethod.cs的主要内容,如果未能解决你的问题,请参考以下文章

csharp 例如-CSHARP-GroupDocs.Conversion.Examples.CSharp渲染,RenderPSDImageAsPath.cs

csharp 实例-CSHARP-GroupDocs.Conversion.Examples.CSharp变频-ConvertTopresentationAsPath.cs

csharp 实例-CSHARP-GroupDocs.Conversion.Examples.CSharp变频-ConvertTopresentationAsPath.cs

csharp 实例-CSHARP-GroupDocs.Conversion.Examples.CSharp变频-ConvertTopresentationAsPath.cs

csharp 例如-CSHARP-GroupDocs.Search.Examples.CSharp索引,AddDocumentToIndex.cs

csharp 例如-CSHARP-GroupDocs.Search.Examples.CSharp索引,AddDocumentToIndexAsynchronously.cs