以常量作为键的对象字面量(在键值对中)
我有一个类,它保存一些常量,并将接收一个对象文字(关联数组),其中包含一些如下数据:
var ConfigObj:Config = new Config({
"Some" : 10,
"Other" : 3,
"Another" : 5
});
该类如下所示:
public dynamic class Config
{
static public const SomeProperty:String = "Some";
static public const OtherProperty:String = "OtherProperty";
static public const AnotherProperty:String = "AnotherProperty";
public function Config(settings:Object)
{
// Doing some stuff here
}
}
问题是,我如何将常量作为传递>keys 像这样:
var ConfigObj:Config = new Config({
Config.SomeProperty : 10,
Config.OtherProperty : 3,
Config.AnotherProperty : 5
});
此外,如果可能的话,我想将其保持内联。
var MyObj:MyClass = new MyClass({x:1, y:2, z:3});
对我来说,远远好于:
var Temp:Object = new Object();
Temp.x = 1; // Or Temp[x] = 1;
Temp.y = 2; // Or Temp[y] = 2;
Temp.z = 3; // Or Temp[z] = 3;
var MyObj:MyClass = new MyClass(Temp);
I have a class that holds some constants and will receive an object literal (associative array) with some data like this:
var ConfigObj:Config = new Config({
"Some" : 10,
"Other" : 3,
"Another" : 5
});
The class looks like this:
public dynamic class Config
{
static public const SomeProperty:String = "Some";
static public const OtherProperty:String = "OtherProperty";
static public const AnotherProperty:String = "AnotherProperty";
public function Config(settings:Object)
{
// Doing some stuff here
}
}
The problem is, how can I pass the constants as keys like this:
var ConfigObj:Config = new Config({
Config.SomeProperty : 10,
Config.OtherProperty : 3,
Config.AnotherProperty : 5
});
Besides, I would like to keep it inline, if possible.
var MyObj:MyClass = new MyClass({x:1, y:2, z:3});
is, for me, far better than:
var Temp:Object = new Object();
Temp.x = 1; // Or Temp[x] = 1;
Temp.y = 2; // Or Temp[y] = 2;
Temp.z = 3; // Or Temp[z] = 3;
var MyObj:MyClass = new MyClass(Temp);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我觉得您的配置对象过于复杂,但是如果您确实想使用常量来设置键值对,则需要使用临时变量:
要问的一个重要问题:这些属性真的是持续的?如果是的话,那么在实例化对象时使用字符串文字几乎没有风险:
当然,如果常量中的值发生变化,这不灵活。
I get the feeling that you're over-complicating your configuration object, however if you do want to use constants to set key-value pairs, you'll need to use a temporary variable:
An important question to ask: are these properties truly constant? If they are, then there's little risk in using the string literal when you instantiate the object:
Of course, this isn't flexible if the values in the constants change.
如果您想强制执行类型检查和参数命名,则不应使用
动态类
或传递Object
,但您应该编写Config类
拥有所有可用的可能性。在设置参数时返回 Config 类将允许您内联调用。
它需要更多的工作,但恕我直言,它更安全。
前任:
If you want to enforce type checking and parameter naming you should not use a
dynamic class
or passing anObject
, but you should code aConfig class
with all the possibilities that are available.Returning the
Config class
while setting a paremeter will allow you to inline the call.It requires more works but it's safer IMHO.
Ex: