0

我有一个从中得到的模型Type。型号为Type BasePage。我可以将其转换/转换为 的类型Type吗?这个页面可以是 10 种不同的类型,所以我真的会从Type该作品的转换/转换中受益。

Type pageType = page.GetType();

//this is what im trying to do but from the Type instead
var newPageOfType = (pageType)pageToCast; //I would usually use this Typecast

更新
用正确的示例代码更新了我的问题。所有pageType类型都派生自同一个BasePage

4

2 回答 2

0

最常见的方法是实际进行演员表,看看它是否像这样成功:

var newPage = page as SomeDerivedPageClass;
if (newPage != null)
{
    // the cast succeeeded, page was actually of the derived type
}
else
    // the passed object wasn't what you were expecting. ignore it,
    // throw an error, log the error, whatever is appropriate.
于 2013-04-01T17:39:30.377 回答
0

只要参数实现IConvertible ,您就可以使用Convert.ChangeTypevalue

Type pageType = page.GetType();
var newPageOfType = Convert.ChangeType(pageToCast, pageType);
于 2013-04-01T17:59:56.170 回答