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