【发布时间】:2012-04-04 14:28:11
【问题描述】:
我想创建一组非常相似并且可以转换为其他类型的类。我的想法是创建一个接口对象并通过基类实现它。然后创建从我的基础继承的其他类。然后我可以使用接口来处理通用(基本)方法,并将对象从 BASE 对象转换为自定义类型。
interface ImyInterface {
}
public class MyBase : ImyInterface {
}
public class MyCustom1 : MyBase {
}
public class MyCustom2 : MyBase {
}
// in helper class
public static MyBase GetGeneralOjbect() {
// get a generic base object
return new MyBase();
}
// How I'm trying to use this
MyCustom1 obj = GetGeneralOjbect() as MyCustom1;
这似乎工作除了对象语句的转换。即使静态帮助程序 GetGeneralOjbect 返回一个良好的 MyBase 对象,MyCustom1 也始终为空。也许这无法完成,或者我没有正确执行。任何意见将不胜感激。
【问题讨论】:
标签: c# class interface casting