仿制药 - 使用类型参数使用getRuntimeThod



试图编写一个UTILTY方法,该方法确定一种类型是否可简化(即具有类似的方法:parse(string value)

下面的代码有效,但似乎有些kludgey:

 public static bool  IsParseable(Type t) {
        string s = "foo";
        Type[] typeArray = { s.GetType() };
        if (t.GetRuntimeMethod("Parse", typeArray )==null) {
            return false;
        } else {
            return true;
        }
    }

似乎应该有一种更好的方法来获取我的手字符串类型,然后必须创建类型(字符串)的实例才能调用getType()

同样出现了尝试使用该方法的出现,如:

bool results = IsParseable(Double); //doesn't compile.

要找出双重解析,我必须做类似的事情。

Double v = 1.0;
Type doubleType = v.GetType();
bool result = IsParseable(doubleType);

有更有效的方法吗?最终,我想将其与通用类型一起使用,其中我有一个类型的参数t,我想找出t是否具有解析(字符串值)方法:

iSparsable(t)

哪个当然也不起作用。而创建t的实例并不是一个很好的解决方案,因为不知道t是否具有默认构造函数。

您可以使用通用方法

public static bool IsParseable<T>() 
{
    var argumentTypes = new[] { typeof(string) };
    var type = typeof(T);
    return type.GetRuntimeMethod("Parse", argumentTypes) != null;
}
// Use it
if (IsParseable<decimal>())
{
    // Parse...
}

或使用托马斯·韦勒(Thomas Weller)的提示使用您的方法,并使方法成为Type的扩展方法(从可读性的角度来看甚至更好(基于意见))。

public static bool IsParseable(this Type type) 
{
    var argumentTypes = new[] { typeof(string) };        
    return type.GetRuntimeMethod("Parse", argumentTypes) != null;
}

然后使用

if (typeof(decimal).IsParseable())
{
   // Do something
}

最新更新