Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为所有数据类型扩展TryParse_C#_.net - Fatal编程技术网

C# 为所有数据类型扩展TryParse

C# 为所有数据类型扩展TryParse,c#,.net,C#,.net,我写了一个函数来检查数据类型int32 public static Int32? ParseInt32(this string text) { Int32 result; if (!Int32.TryParse(text, out result)) return null; return result; } 如何扩展此支持所有数据类型的函数 谢谢。因此,您可

我写了一个函数来检查数据类型int32

 public static Int32? ParseInt32(this string text)
        {
            Int32 result;
            if (!Int32.TryParse(text, out result))
                return null;
            return result;
        }
如何扩展此支持所有数据类型的函数


谢谢。

因此,您可以使用泛型,但在方法体中,您需要使用类型在特定的数据类型中解析它


您可以检查这一点:

很好,因为您可以使用泛型,但是在方法体中,您需要使用类型在特定的数据类型中解析它


你可以检查一下:

像这样的东西怎么样:

public static T? TryParse<T> (this string text) where T: struct
{
    T? result = null;

    if (!string.IsNullOrEmpty(text))
    {
        try
        {
            result = (T?) Convert.ChangeType(text, typeof (T));
        }
        catch (InvalidCastException) {}
        catch (FormatException) {}
        catch (OverflowException) {}
    }

    return result;
}
int? myInt = "100".TryParse<int>();
publicstatict?TryParse(此字符串文本),其中T:struct
{
T?结果=空;
如果(!string.IsNullOrEmpty(text))
{
尝试
{
结果=(T?)Convert.ChangeType(text,typeof(T));
}
catch(InvalidCastException){}
捕获(格式化异常){}
捕获(溢出例外){}
}
返回结果;
}
然后你会这样称呼它:

public static T? TryParse<T> (this string text) where T: struct
{
    T? result = null;

    if (!string.IsNullOrEmpty(text))
    {
        try
        {
            result = (T?) Convert.ChangeType(text, typeof (T));
        }
        catch (InvalidCastException) {}
        catch (FormatException) {}
        catch (OverflowException) {}
    }

    return result;
}
int? myInt = "100".TryParse<int>();
int?myInt=“100”。TryParse();

DateTime?myDate=“2001-01-01T23.00.00”;

像这样的东西怎么样:

public static T? TryParse<T> (this string text) where T: struct
{
    T? result = null;

    if (!string.IsNullOrEmpty(text))
    {
        try
        {
            result = (T?) Convert.ChangeType(text, typeof (T));
        }
        catch (InvalidCastException) {}
        catch (FormatException) {}
        catch (OverflowException) {}
    }

    return result;
}
int? myInt = "100".TryParse<int>();
publicstatict?TryParse(此字符串文本),其中T:struct
{
T?结果=空;
如果(!string.IsNullOrEmpty(text))
{
尝试
{
结果=(T?)Convert.ChangeType(text,typeof(T));
}
catch(InvalidCastException){}
捕获(格式化异常){}
捕获(溢出例外){}
}
返回结果;
}
然后你会这样称呼它:

public static T? TryParse<T> (this string text) where T: struct
{
    T? result = null;

    if (!string.IsNullOrEmpty(text))
    {
        try
        {
            result = (T?) Convert.ChangeType(text, typeof (T));
        }
        catch (InvalidCastException) {}
        catch (FormatException) {}
        catch (OverflowException) {}
    }

    return result;
}
int? myInt = "100".TryParse<int>();
int?myInt=“100”。TryParse();

DateTime?myDate=“2001-01-01T23.00.00”;

以下是一个简单的工作示例:

using System;

namespace ConsoleApplication1
{
    struct Test
    {
        // No TryParse method here!
    }

    static class Program
    {
        static void Main(string[] args)
        {
            var invalidTest = "12345".ParseTo<DateTime>();
            var validTest = "12345".ParseTo<int>();
            var veryInvalidTest = "12345".ParseTo<Test>();

            Console.WriteLine(!invalidTest.HasValue ? "<null>" : invalidTest.Value.ToString());
            Console.WriteLine(!validTest.HasValue ? "<null>" : validTest.Value.ToString());
        }

        public static T? ParseTo<T>(this string test) where T : struct
        {
            var method = typeof(T).GetMethod("TryParse", new Type[] { typeof(string), typeof(T).MakeByRefType() });

            if (method == null)
                throw new Exception(); // or return null or whatever

            var parameters = new object[] { test, null };

            if ((bool)method.Invoke(null, parameters))
            {
                return (T)parameters[1];
            }
            else
                return null;
        }
    }
}
使用系统;
命名空间控制台应用程序1
{
结构测试
{
//这里没有TryParse方法!
}
静态类程序
{
静态void Main(字符串[]参数)
{
var invalidTest=“12345”。ParseTo();
var validTest=“12345”。ParseTo();
var veryInvalidTest=“12345”。ParseTo();
Console.WriteLine(!invalidTest.HasValue?“:invalidTest.Value.ToString());
Console.WriteLine(!validTest.HasValue?”“:validTest.Value.ToString());
}
公共静态T?ParseTo(此字符串测试),其中T:struct
{
var method=typeof(T).GetMethod(“TryParse”,新类型[]{typeof(string),typeof(T).MakeByRefType()});
if(方法==null)
抛出新异常();//或返回null或其他值
var参数=新对象[]{test,null};
if((bool)method.Invoke(null,参数))
{
返回(T)参数[1];
}
其他的
返回null;
}
}
}

以下是一个简单的工作示例:

using System;

namespace ConsoleApplication1
{
    struct Test
    {
        // No TryParse method here!
    }

    static class Program
    {
        static void Main(string[] args)
        {
            var invalidTest = "12345".ParseTo<DateTime>();
            var validTest = "12345".ParseTo<int>();
            var veryInvalidTest = "12345".ParseTo<Test>();

            Console.WriteLine(!invalidTest.HasValue ? "<null>" : invalidTest.Value.ToString());
            Console.WriteLine(!validTest.HasValue ? "<null>" : validTest.Value.ToString());
        }

        public static T? ParseTo<T>(this string test) where T : struct
        {
            var method = typeof(T).GetMethod("TryParse", new Type[] { typeof(string), typeof(T).MakeByRefType() });

            if (method == null)
                throw new Exception(); // or return null or whatever

            var parameters = new object[] { test, null };

            if ((bool)method.Invoke(null, parameters))
            {
                return (T)parameters[1];
            }
            else
                return null;
        }
    }
}
使用系统;
命名空间控制台应用程序1
{
结构测试
{
//这里没有TryParse方法!
}
静态类程序
{
静态void Main(字符串[]参数)
{
var invalidTest=“12345”。ParseTo();
var validTest=“12345”。ParseTo();
var veryInvalidTest=“12345”。ParseTo();
Console.WriteLine(!invalidTest.HasValue?“:invalidTest.Value.ToString());
Console.WriteLine(!validTest.HasValue?”“:validTest.Value.ToString());
}
公共静态T?ParseTo(此字符串测试),其中T:struct
{
var method=typeof(T).GetMethod(“TryParse”,新类型[]{typeof(string),typeof(T).MakeByRefType()});
if(方法==null)
抛出新异常();//或返回null或其他值
var参数=新对象[]{test,null};
if((bool)method.Invoke(null,参数))
{
返回(T)参数[1];
}
其他的
返回null;
}
}
}

所有数据类型?日期时间如何<代码>过程<代码>SqlException?所有这些都是类型。您可以使用泛型和反射,但所有数据类型可能都不支持TryParse方法。所以在运行时调用它们可能会导致异常。因此,请具体说明您希望支持哪种数据类型?只需int、DateTime、Long,Double@mohsen:所有这些类型都已具有TryParse方法。所有数据类型?日期时间如何<代码>过程<代码>SqlException?所有这些都是类型。您可以使用泛型和反射,但所有数据类型可能都不支持TryParse方法。所以在运行时调用它们可能会导致异常。因此,请具体说明您希望支持哪种数据类型?只需int、DateTime、Long,Double@mohsen:所有这些类型都已经有了一个TryParse方法。如果无法转换,将引发异常(尽管
Convert.ChangeType
,我不知道有这个方法)。谢谢George,我一点击save就意识到了这一点。更新以捕获解析异常。与int.TryParse、datetime.TryParse、long.TryParse、double.TryParse等相比,此方法有什么优势。??看来你在发明轮子!如果无法转换,则会引发异常(尽管
Convert.ChangeType
使用得很好,但我不知道会发生异常)。谢谢George,我一点击save就意识到了这一点。更新以捕获解析异常。与int.TryParse、datetime.TryParse、long.TryParse、double.TryParse等相比,此方法有什么优势。??看来你在发明轮子!