简体   繁体   中英

How to cast an object of type Object to a object of type T?

I've written a method that executes JavaScript and return value. The returned value could be literately anything. Now I'd like at least to cut the number of repeated code by writing an generic overload.

something like:

public T ExecuteJavascriptWithReturnValue<T>(string js)
{
 object obj = ExecuteJavascriptWithReturnValue(js); --the original method returns an object
 if (typeof(T) == typeof(int) || typeof(T) == typeof(double) ||typeof(T) == typeof(string))
      return (T)(obj);
}
else
{
   throw new Exception("For objects other than int, float, double, or string, please use the non generic version.");
}

I'm getting the the following error: specified cast is not valid . The only time this code works is when the object returned is of type string .

Thanks for helping.

EDIT

public object ExecuteJavascriptWithReturnValue(string js)
{
   IJavaScriptExecutor jse = driver as IJavaScriptExecutor;
   object result = jse.ExecuteScript(js);
   return result;
}

This method can return litteraly anything, for instance, a collections, a string, a number, etc. Here's the metadata:

...object ExecuteScript(string script, params object[] args);

and a script could be something like:

string js = "return $('#calculateValueStep > span.k-widget.k-numerictextbox > span >"
          + " input.k-formatted-value.k-input').val();";

I use this method often. So, I want a generic method for those time I'm expecting an object of type, such as int, double, and son forth.

也许试试这个:

 return (T)Convert.ChangeType(obj, typeof(T));

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