简体   繁体   English

如何将对象类型的对象转换为类型T的对象?

[英]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. 我编写了一种执行JavaScript并返回值的方法。 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 . 我收到以下错误: specified cast is not valid The only time this code works is when the object returned is of type string . 此代码只有在返回的对象为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. 因此,我希望在那些期望类型为int,double和son之类的对象的时候使用通用方法。

也许试试这个:

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

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

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