简体   繁体   中英

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)

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()

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 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:

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.

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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