[英]Validate strings as Int32 or Int64
我使用以下代碼來驗證來自ajax調用的收入數字:
public Tuple<bool, int> ValidateInt(string TheCandidateInt)
{
int TheInt = 0;
if (Int32.TryParse(TheCandidateInt, out TheInt))
{
return new Tuple<bool, int>(true, TheInt);
}
else
{
return new Tuple<bool, int>(false, 0);
}
}
public Tuple<bool, short> ValidateShort(string TheCandidateShort)
{
short TheShort = 0;
if (Int16.TryParse(TheCandidateShort, out TheShort))
{
return new Tuple<bool, short>(true, TheShort);
}
else
{
return new Tuple<bool, short>(false, 0);
}
}
對於Byte
和Short
我也有相同類型的函數。 如您所見,我傳入一個字符串,返回值是一個元組,其中Item1是布爾值,而Item2是值。
有沒有辦法將這4種方法更改為1,並以某種方式將解析的數據類型分解出來?
謝謝。
您可以使用泛型將方法合並為一種:
public static Tuple<bool, T> ValidateValue<T>(string input) where T : struct
{
T result = default(T);
try
{
result = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(input);
}
catch
{
return new Tuple<bool, T>(false, result);
}
return new Tuple<bool, T>(true, result);
}
至於分析的數據類型,您仍然必須將其指定為通用參數。
ValidateValue<byte>("255");
您可以創建一個封裝了TryParse調用的委托,從而創建一個更通用的驗證方法版本。 下面的示例顯示了大綱:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestTryParseDelegate
{
class Program
{
private delegate bool TryParseDelegate<T>(string candidate, out T result)
where T : struct;
private static Tuple<bool, T> Validate<T>(string candidate, TryParseDelegate<T> tryParseDel)
where T : struct
{
T result;
return Tuple.Create(tryParseDel(candidate, out result), result);
}
public static Tuple<bool, int> ValidateInt(string TheCandidateInt)
{
return Validate<int>(TheCandidateInt, int.TryParse);
}
public static void Main()
{
var result = ValidateInt("123");
Console.WriteLine(result);
}
}
}
我仍然建議像您的示例一樣,將通用版本封裝在專用方法中,因為委托是您可能不希望發布的實現細節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.