简体   繁体   中英

Get MethodInfo of String.Trim with reflection?

I can get MethodInfo of String.Trim as follows, It's OK but gotten method info doesn't have a string parameter! Is it OK?

typeof(string).GetMethod("Trim", new Type[ ] {});

The following code return null, why?:

typeof(string).GetMethod("Trim", BindingFlags.Public);

And how can we use (invoke) Trim method info?

When you do typeof(string).GetMethod("Trim", new Type[ ] {}); , you are asking to retrieve the overload of the method which does not take any parameters. That is why there is no parameter shown in the output. If instead you do this typeof(string).GetMethod("Trim", new Type[ ] {typeof(char[])}); , it will return the corresponding overload.

Regarding the second issue, you can overcome this problem by setting the flag for indicating instance method ie BindingFlags.Public|BindingFlags.Instance . This will however, merely change the error to an ambiguous match issue. I would suggest you pass in the parameter type list as well to overcome that.

Since in your first example, you specifically ask for a method that has no parameters, you get the overload without any parameters.

If you want the overload with parameters, you need to say so:

typeof(string).GetMethod("Trim", new [] { typeof(char[]) });

To invoke an instance method via MethodInfo , you need to pass the instance reference to the Invoke() method:

// Parameterless overload
methodInfo.Invoke(myStringInstance, null);

// Single-parameter overload
methodInfo.Invoke(myStringInstance, new [] { new [] { ' ', '\r', '\n' } });

In your second example, you specified neither BindingFlags.Instance or BindingFlags.Static , so (as documented) the method returned null . Specify one or the other ( BindingFlags.Instance for the Trim() method) to get a valid return value (assuming only one method matches...in this case, there is more than one so you'll get an error).

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