基于类型返回特定对象的通用工厂方法 [英] Generic factory method to return specific object based on type

查看:34
本文介绍了基于类型返回特定对象的通用工厂方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下基类:

public abstract class ItemComponentSaver<TType> : where TType : ItemComponent
{
    public abstract bool SaveItem(TType item, object objectRowInTableFromEF, PropertyInfo columnTypeProperty);
}

对于我支持的每种类型,这个也有一些子项.我的想法是多态地使用它们来执行稍后的保存操作,例如

This one, also has some children, for each of the types that I support. My idea is to use them polymorphically to perform a save operation later on, for example

    public class CellSaver : ItemComponentSaver<Cell>
    {
        public override bool SaveItem(Cell item, object objectRowInTableFromEF, PropertyInfo columnTypeProperty)
        {
                // code here
        }
    }

现在,我知道在某个时候我需要创建这些东西,所以有一个不可避免的开关"之类的语句,我为此创建了一个工厂:

Now, I know that at some point I need to create this stuff, so there's the unavoidable "switch" like statement, I craeted a factory for this:

public static class ItemComponentSaverFactory
{
    public static ItemComponentSaver<T> GetSaver<T>(ItemComponent entity) where T : ItemComponent
    {
        if (entity is Cell)
            return (ItemComponentSaver<T>)new CellSaver();

        if (entity is Row)
            return (ItemComponentSaver<T>)new RowSaver();
    }

}

问题是,我无法将 CellSaver 转换为返回类型,因为它是通用的.我也可以返回一个接口而不是类 tpe,但是当然,如​​果我创建接口,我也需要使它成为通用的,因为返回类型是这样的我该如何优雅地处理这种情况?

The problem is, I can't cast the CellSaver to the return type, because it's generic. I could also return an interface instead of the class tpe, but of course, if I create the interface, I need to make it generic as well, because the return type is like that How can I handle this case in an elegant way??

推荐答案

此设计还有其他选项,但由于我们不知道您尝试执行的操作的内部结构,因此我的回答将仅基于所提供的代码.您可以像这样重写 GetSaver 方法:

There are other option for this design,but since we dont know the internals of what you are trying to do my answer will be based only with the presented code. You can rewrite your GetSaver method like this:

     public static ItemComponentSaver<T> GetSaver<T>() where T : ItemComponent
     {
         if (typeof(T) == typeof(Cell))
             return new CellSaver() as ItemComponentSaver<T>;
         else if (typeof(T) == typeof(Row))
             return new RowSaver() as ItemComponentSaver<T>;
         else
             return null;//here you can return what u need in case no types match.
     }

这样称呼...

ItemComponentSaver<Row> saver = ItemComponentSaverFactory.GetSaver<Row>();

这篇关于基于类型返回特定对象的通用工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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