动态选择Class以便在程序中使用。 [英] Dynamically selecting Class for use in program.

查看:61
本文介绍了动态选择Class以便在程序中使用。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有10个只保存数据的类。 int和字符串数据。没什么好看的。


然而。我有10个可供用户选择。

根据选择。我想实例化一个特定的类。

Ver是数据类所在的命名空间。


我没有这个接口,并且我不确定我是否应该这样做。所有10个类都将具有完全相同的变量名称。只是不同的内部数据。

我将为此运行一个巨大的循环(132次)。所以我宁愿使用这种声明CurrentV的动态方法,所以我不必重复10次相同的代码。

展开 | 选择 | Wrap | 行号

解决方案

所以这10个类都来自同一个基类?那样他们继承了所有这些相同的属性吗?


除了tlhintoq所说的(你需要使用基类)你的代码没有的原因工作是因为你在开关块中定义了CurrentV。当您退出时,您将超出范围并丢失数据:)


这就是您需要基本类型的原因,因此您可以在switch语句中为其分配通用数据。此外,你仍然可以告诉它是什么类型...


例如:

展开 | 选择 | 换行 | 行号


我从来没有真正得到过继承概念。

此外,我在这些课程中没有任何方法。它只是数据变量。


呃。我迷路了。 = \

I have 10 Classes that just hold data. int and string data. Nothing fancy.

Yet. I have 10 possible selections from the user.
Based on the selection. I want to Instantiate a specific class.
Ver is the namespace the Data Classes are within.

I don''t have an Interface for this, and am not sure if I should. All 10 classes will have the exact same name for the variables. Just different internal data.
I''ll be running a huge loop (132 times) for this. So I would rather have this Dynamic method of declaring CurrentV so I don''t have to do 10 repeats of the same code.

Expand|Select|Wrap|Line Numbers

解决方案

So all of these 10 classes are derived from the same base class? That way they inherit all of these identical properties?


In addition to what tlhintoq said (you will need to use a base class) the reason your code doesn''t work is because you''re defining CurrentV in the switch block. When you exit, you go out of scope and lose your data :)

This is why you need the base type, so you can assign your generic data to it in your switch statement. Additionally, you can still tell what type it is...

example:

Expand|Select|Wrap|Line Numbers


I never really did get the Inheritance concepts really.
Also I don''t have any methods within these classes. Its all just data variables.

Ugh. Im lost. =\


这篇关于动态选择Class以便在程序中使用。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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