[英]Flex/AS3 Dynamically Create class
I need to create somethink like this. 我需要创建这样的想法。
var s:String;
var b1:Boolean;
if (b1==true)
s="Class1()"
else
s="Class2()";
var o:Object;
o = new [s]() // create or new Class1(), or new Class2
You haven't given much information so I don't know if you really need to do this, but there are a few good reasons you might, and it can be done using getDefinitionByName
: 您没有提供太多信息,所以我不知道您是否真的需要这样做,但是有一些很好的理由,您可以使用
getDefinitionByName
来完成:
var className:String = somethingIsTrue ? "Class1" : "Class2";
var classType:Class = getDefinitionByName(className) as Class;
if (classType)
trace(new classType());
Note that: 注意:
"path.to.my.stuff.Class1"
"path.to.my.stuff.Class1"
getDefinitionByName
will not find it. getDefinitionByName
将找不到它。 The easiest way to solve this is to put a type declaration somewhere, such as var a:Class1, b:Class2
. var a:Class1, b:Class2
。 Another way is to put those classes in a swc
library. swc
库中。 getDefinitionByName
is very slow (thanks @Philarmon), so to be clear: avoid this unless you really have to do it. getDefinitionByName
的速度非常慢(感谢@Philarmon),因此请清楚:除非确实需要这样做,否则避免这样做。 EDIT : Here's an example of how you can do it without using a string: 编辑 :这是一个无需使用字符串即可完成此操作的示例:
var classType:Class = somethingIsTrue ? Class1 : Class2;
var instance:Object = new classType();
As you can see, you don't have to use a string if you actually know the class name ahead of time. 如您所见,如果您确实提前知道了类名,则不必使用字符串。 In fact cases where you don't know the class name ahead of time is rare.
事实上情况下,你不知道提前的类名是罕见的。
Even if you are starting with a string (say from JSON serialized user data), as long as you know the class names ahead of time you can map the strings to class references: 即使您以字符串开头(例如从JSON序列化的用户数据中),只要您提前知道了类名,就可以将字符串映射到类引用:
var classes:Object = {
"alfa": Class1,
"bravo": Class2
}
var className:String = "alfa";
var instance:Object = new classes[key];
Without knowing the reasoning behind your situation, most likely what you are looking for is an Interface. 在不了解情况背后的原因的情况下,最有可能需要的是接口。 First create an interface (see here for an example):
首先创建一个接口(请参阅此处的示例):
public interface MyInterface {
//Include any methods the classes should implement here
}
Then each class should implement that interface: 然后,每个类都应实现该接口:
public class Class1 implements MyInterface
And finally, when creating them, you can do it like this: 最后,在创建它们时,您可以这样做:
var o:MyInterface;
if (b1 == true)
o = new Class1();
else
o = new Class2();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.