请教C#中用工厂模式管理对象时如何调用子类里特有的方法

xiaoyu_xh xiaoyu_xh 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
小弟新学C#,最近在研究打印的东西(主要就是打印字符串的),内容里包含有一块是列表内容
为了以后方便扩展,我的基本想法是在基类里只定义了字体,和系统提供的一个Drawing函数,大致如下:
class Composition
{
private string _name;
private string _content;
private string _fontName;
private string _fontSize;

public string Name
{
set { _name = value; }
get { return _name; }
}

public string Content
{
set { _content = value; }
get { return _content; }
}
public string FontName
{
set { _fontName = value; }
get { return _fontName; }
}
public string FontSize
{
set { _fontSize = value; }
get { return _fontSize; }
}

public virtual void Drawing(PrintPageEventArgs e, ref float _yPosition)
{

}
}
然后打印内容中的每一块继承该基类实现自己的画图过程;
由于打印内容中有一块是列表(该表业务逻辑关联性较大,所以觉得拆开打印不是很好),因此这块传入的内容大致为一个结构数组,因此我在这个子类里新建了一些设置的方法
public Menulist[] MenuNames
{
set { _menuNames = value; }
get { return _menuNames; }
}
public Menulist[] MenuContents
{
set { _menuContents = value; }
get { return _menuContents; }
}


一些静态不变的东西我是放在xml文件里处理的,然后我目前是按照简单工厂模式的管理方式
public static Composition CallPrint(compositionType enumComTypePara)
{
Composition printComposition = null;
switch (enumComTypePara)
{
case compositionType.Title:
printComposition = new TitleComposition();
break;
case compositionType.Index:
printComposition = new IndexComposition();
break;
case compositionType.UserName:
printComposition = new UsernameComposition();
break;
case compositionType.Time:
printComposition = new TimeComposition();
break;
case compositionType.Menu:
printComposition = new MenulistComposition();
break;
case compositionType.Totle:
printComposition = new TotleComposition();
break;
case compositionType.Footer:
printComposition = new FooterComposition();
break;
default:

break;
}

return printComposition;
}

现在碰到的问题就是,因为这里的对象printComposition是从基类的对象,所以调用时编译器无法识别出子类(列表那个类)中特有的方法,在C++中可以通过对象指针的方式强行指定到子类里,不知道C#中是怎么处理的,还是说我这个架构在C#中就不合理呢?
...全文

相关推荐

评论 2
收藏 已收藏
分享
返回顶部
xiaoyu_xh
C# 111,129 成员 642,539 内容