Type Casting and the Factory pattern

前端 未结 4 1438
执笔经年
执笔经年 2020-12-14 13:15

I\'m having a hard time figuring out how to implement a factory pattern in a DTO mapper I\'m trying to create. I\'m pretty sure I need to rethink my design. Here is a very s

4条回答
  •  一向
    一向 (楼主)
    2020-12-14 13:28

    Do you have to use a string to communicate the type you want? You could use generics instead:

    public static T CreatePerson() where T : Person
    

    Now it's hard to say exactly whether this will work or not, because we don't know the details of what you'd really be doing within CreatePerson. If it's just calling a parameterless constructor, that's easy:

    public static T CreatePerson() where T : Person, new()
    {
        return new T();
    }
    

    However, that's also reasonably pointless as the caller could do that instead. Is generics viable in your actual situation? If not, could you explain why not, and we could try to work around it?

提交回复
热议问题