简体   繁体   中英

how to change an object type to its actual type?

I have an object which is actually string/integer. I can get its type by obj.GetType(). In the runtime I know it is a string. The problem is a function only accepts string or integer. If I wrote

int cnt = 0;
public object why()
{
    cnt++;
    if (cnt % 2 == 0) return 0;
    return "";
}
void A(int input) {
}
void A(string input) {
}
void Test()
{
    object obj = why();
    MethodInfo method = obj.GetType().GetMethod(nameof(A), new[] { obj.GetType() });
    //Need to call A by obj, but it threw an error :)
    method.Invoke(null, new[] { obj });
}

It returns error as it rejects object. It could work if

func((string)obj)

But I need also cater integer ( and possibly other type too later, thus it may not appropriate to apply conditional statement for the scenario)

the optimum way is changing the type of the object before assign it to the function, but I am not sure if it is possible, which is string in the example func((string)obj).

You can use reflection to get the correct method based on the type of the object. Then you can use Invoke() to actually call the method with the argument.

object obj = why();
MethodInfo method = typeof(YourClass).GetMethod(nameof(YourClass.A), new [] { obj.GetType() } );
method.Invoke(maybe_an_object_here, new [] { obj } );
  • The class YourClass is the class which contains the method A .
  • maybe_an_object_here is the object instance of YourClass on which you want to call the A method on. Depending on what you are doing this argument can be this (if it is an object of YourClass ). In case it is a static method (it is not according to your code provided) you do not provide an object of that class but instead use the value null since you don't need objects to call static methods.

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