来自Type的Typecast。从Type转换为model

时间:2013-04-01 17:22:40

标签: c# casting

我有一个模型,我从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

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:0)

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

Type pageType = page.GetType();
var newPageOfType = Convert.ChangeType(pageToCast, pageType);