转换/投基类型派生类型 [英] Convert/Cast base type to Derived type

查看:131
本文介绍了转换/投基类型派生类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过派生它扩展现有的.NET Framework类。我如何基本类型的对象转换为派生类型?

I am extending the existing .NET framework class by deriving it. How do I convert an object of base type to derived type?

public class Results { //Framework methods }

public class MyResults : Results { //Nothing here }

//I call the framework method

public static MyResults GetResults()
{
    Results results = new Results();
    //Results results = new MyResults(); //tried this as well.

    results = CallFrameworkMethod();

    return (MyResults)results; //Throws runtime exception
}

据我所知,这种情况发生,因为我想投一个基本类型,以派生类型,如果派生类型具有附加属性,那么内存不分配。当我添加额外的属性,我不在乎,如果他们被初始化为null。

I understand that this happens as I am trying to cast a base type to a derived type and if derived type has additional properties, then the memory is not allocated. When I do add the additional properties, I don't care if they are initialized to null.

我如何做到这一点没有做手工拷贝?

How do I do this without doing a manual copy?

推荐答案

您不能。如果结果不引用一个 MyResults (例如,如果 CallFrameworkMethod 返回一个基本结果实例),然后浇铸不会让这样:你需要创建一个新的 MyResults 的基础上,现有的非 - MyResults 。铸造是关于更改的引用的,而不是要改变的具体类型的引用对象。

You can't. If results doesn't refer to a MyResults (e.g. if CallFrameworkMethod returns a base Results instance), then casting won't make it so: you'll need to create a new MyResults, based on the existing non-MyResults. Casting is about changing the compile-time type of the reference, not about changing the concrete type of the referenced object.

您可以使用如反射或AutoMapper工具,以帮助新 MyResults 对象的初始化 - 而是一个新的 MyResults 对象一定有,因为你不能告诉一个基地结果的对象,成为 MyResults 对象。

You can use tools such as Reflection or AutoMapper to help with the initialisation of the new MyResults object -- but a new MyResults object there must be, because you cannot tell a base Results object to become a MyResults object.

这篇关于转换/投基类型派生类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆