English 中文(简体)
B. 关于使用班子创建班级的方案建议
原标题:Programming advice on creating a class using class name

在大韩民国,我询问并看到了如何使用其名称建立一间班的问题。 我的问题并不相同,因此我会问这个问题。

我的申请分为两类,即“A”和“B”。 在另一个类别中,我需要使用这两个类别(第三类是外部服务机构要求的)。 外部服务只能把两个“A”和“B”类的名称作为座标。 在第三类中,我知道我可以做以下事情:

case "A":
    create an instance of A
case "B":
    create an instance of B

but that seems weird. I d like to do it dynamically so I was thinking of doing Activator.CreateInstance but not sure if it s good programming because it seems "CreateInstance" is used when you load an assembly remotely. In my case, everything is in one project.

任何建议? 谢谢你!

最佳回答

This is perfect case for using Factory Method pattern.

http://www.dofactory.com/Patterns/PatternFactory.aspx

问题回答

If number of classes that you want to create by their name is limited (such as 2 different classes in your example), I would prefer the way with "switch"

public object ClassFactory(string ClassName)
{
    switch(ClassName)
    {
        case "A": return new A();
        case "B": return new B();
    }
}

因为它既快捷又更安全(如果班级的名称来自外部服务,想象会发生什么,如果这一服务会带来恶名)。

否则,启动者。 创造活力不应造成任何问题,但应确保你彻底核实投入。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签