我正在尝试编写一个验证方法。例如:对于 double,它看起来像这样:
protected bool ValidateLoopAttributes(string i_value, double i_threshold)
{
double result;
if (!(double.TryParse(i_value, out result) && result >= i_threshold))
{
return false;
}
return true;
}
是否可以这样写:
protected bool ValidateLoopAttributes<T>(string i_value, T i_threshold)
然后使用类似
的东西 T.GetType().TryParse() // how can i use here the type's methods??
使用 switch/if 语句是唯一的方法吗?例如:
If (T.GetType() is int)
Int32.TryParse(i_threshold)
有没有更优雅的方式?
最佳答案
试试这个:
static class Ext
{
public static bool TryParse<T>(string s, out T value)
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
try
{
value = (T)converter.ConvertFromString(s);
return true;
}
catch
{
value = default(T);
return false;
}
}
public static bool ValidateLoopAttributes<T>(string i_value, T i_threshold)
where T : IComparable
{
T outval;
if (TryParse<T>(i_value, out outval))
return outval.CompareTo(i_threshold) >= 0;
else return false;
}
}
我的回答使用了 Marc Gravell 的回答,摘自 here .
有了这个你可以做
bool b1 = Ext.ValidateLoopAttributes<int>("5", 4);
bool b2 = Ext.ValidateLoopAttributes<double>("5.4", 5.5d);
如果你觉得有用你也可以使用扩展方法
public static bool ValidateLoopAttributes<T>(this string i_value, T i_threshold)
where T : IComparable { }
引导你使用
bool b1 = "5".ValidateLoopAttributes<int>(4);
bool b2 = "5.4".ValidateLoopAttributes<double>(5.5d);
关于c# - 验证 int, double 的通用方法。如何使用 GetType()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10137848/