c# - 验证 int, double 的通用方法。如何使用 GetType()?

标签 c# generics

我正在尝试编写一个验证方法。例如:对于 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/

相关文章:

c# - 从一个数组中删除其索引存在于另一个数组中的元素

java - 通过接口(interface)覆盖泛型方法

java - 谁能解释为什么 listAdapter 不采用通用参数?

c# - LINQ to 对象基础

c# - 如何从 WebMethod 访问全局变量?

c# - 信号R : Access Hub class from another project

c# - C# 中的泛型类型

java - 将 Comparable<T> 与泛型类一起使用

ios - 协议(protocol)类型的异构混合,包括通用协议(protocol)

c# - 如何在 Visual Studio 插件的输出窗口中显示控制台输出?