简体   繁体   English

泛型-使用带有类型参数的GetRuntimeMethod

[英]Generics - using GetRuntimeMethod with type parameter

Trying to write a utilty method which determines whether a type is parseable (ie has a method like: Parse(string value) 尝试编写一种确定类型是否可解析的实用方法(即具有类似以下方法的方法:Parse(string value)

The code below works, but seems a bit 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;
        }
    }

It seems like there should be a better way to get my hands on String type then having to create an instance of the type (string) in order to call GetType() 似乎应该有一种更好的方法来使我接触String类型,然后必须创建该类型(字符串)的实例才能调用GetType()

This likewise comes up trying to use the method, as in: 同样尝试使用该方法,如下所示:

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

Instead to find out if double is parseable, I have to do something like. 而不是找出double是否可解析,我必须做类似的事情。

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

Is there a more efficient way? 有没有更有效的方法? Ultimately I want to use this with generic types, where I have a type parameter T and I want to find out if T has a Parse(String value) method: 最终,我想将其用于泛型类型,其中我具有类型参数T,并且我想确定T是否具有Parse(String value)方法:

IsParseable(T) IsParseable(T)

which of course doesn't work either. 当然哪个也不起作用。 And creating an instance of T isn't a great solution because not known if T has a default constructor. 创建T的实例不是一个很好的解决方案,因为不知道T是否具有默认构造函数。

You can use generic approach 您可以使用通用方法

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...
}

Or use your approach with Thomas Weller's hint and make method an extension method for Type (even better from readability point of view (opinion based)). 或者将您的方法与Thomas Weller的提示结合使用,并使方法成为Type的扩展方法(从可读性的角度(基于观点)甚至更好)。

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

Then use 然后使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM