c# – 从基类创建派生类的实例
发布时间:2020-12-15 23:44:09 所属栏目:百科 来源:网络整理
导读:我有我的抽象基类A: public abstract class A : ICloneable { public int Min { get; protected set; } public int Max { get; protected set; } public A(int low,int high) { this.Min = low; this.Max = high; } //... public object Clone() { return n
我有我的抽象基类A:
public abstract class A : ICloneable { public int Min { get; protected set; } public int Max { get; protected set; } public A(int low,int high) { this.Min = low; this.Max = high; } //... public object Clone() { return new this(this.Min,this.Max); //<-- ?? } } 我的B级扩展了哪个: public class B : A { public B(int low,int high) : base(low,high) { } //... } 由于A是抽象的,因此无法实例化,但派生类可以. 假设类A有许多派生类,它将如何知道实例化哪一个? 好吧,我想实例化我目前A的同一个类(或类型). 也就是说,如果我从B类调用Clone方法,我想实例化一个新的B. 我的方法是写一些类似于: return new this(this.Min,this.Max); 但这似乎不起作用也不编译. 是否有可能在C#中实现这一目标? 如果不是,是否有解释所以我能理解? 解决方法
虽然我喜欢Jamiec解决方案,但我错过了使用反射的脏解决方案:)
public class A { public object Clone() { var type = GetType().GetConstructor(new[] { typeof(int),typeof(int) }); return type.Invoke(new object[] { this.Min,this.Max }); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- The Swift Programming Language学习笔记(八)——闭包
- crossdomain.xml配置说明
- ios – ld:4个用于架构armv7 FireBase Google的重复符号
- Cocos开发中性能优化工具介绍之使用Windows任务管理器
- c# – 触发并忘记异步任务方法有时不会调用
- c# – Windows 7 .NET 4.0中“Marshal.StructureToPtr”的访
- 如何优化cocos2d/x程序的内存使用和程序大小
- iphone – 如何在xcode 4.3中将项目或库导入ios应用程序
- Flex使用Popupmanager弹出窗口的交互传值方法
- Ajax遍历jSon后对每一条数据进行相应的修改和删除(代码分享