在 ColdFusion 组件内,我这样声明一个函数:
string function render(required Array actions) output=false {
//...
}
因此,函数参数只能接受数组。但是,我需要确保数组仅包含“ActionItem”对象(有一个ActionItem.cfc组件)。
ColdFusion中是否有一种方法来对数组内容进行类型提示?在这种情况下,您建议采用什么解决方案?
在 ColdFusion 组件内,我这样声明一个函数:
string function render(required Array actions) output=false {
//...
}
因此,函数参数只能接受数组。但是,我需要确保数组仅包含“ActionItem”对象(有一个ActionItem.cfc组件)。
ColdFusion中是否有一种方法来对数组内容进行类型提示?在这种情况下,您建议采用什么解决方案?
component ArrayCollection()
{
public function init()
{
variables.collection = [];
return this;
}
public any function get();
public function set(required array collection);
public function add(required any item);
public function remove();
}
component ActionItemCollection extends ArrayCollection
{
public function add(required ActionItem item);
public ActionItem function get();
}
component otherComponnet{
public string function render(required ActionItemCollection actions)
{
}
}
在某些情况下可能有些过度,但它允许您强制执行数组中的项目类型!
ActionItemCollection.cfc
,其中包含ActionItems
数组,并让ActionItemCollection.cfc
仅接受ActionItem
对象,因此当您的render()
函数接收到其ActionItemCollection
参数时,“知道”集合中的每个元素绝对是ActionItem
。render()
检查元素是否合法并在不合法时抛出异常时,这可能需要大量工作。这不是完美的解决方案,但CF正在创建一个不完美的情况,所以还算公平。SomeObject
的组件。<cffunction name="testArrayTypeValidation">
<cfargument name="someObjects" type="SomeObject[]" required="yes">
<cfdump var="#someObjects#">
</cffunction>
接着像这样调用我们的函数:
<cfset testArrayTypeValidation([new SomeObject()])>
然而,需要注意的是它只会验证数组中第一个项目的类型,这意味着以下内容也可以正常工作:
<cfset testArrayTypeValidation([new SomeObject(), 'some string'])>
type="string[]"
,这有点令人失望。
output=false
- 除非您明确使用 writeOutput/writeDump 等输出内容,否则它不会输出任何内容。 - Peter BoughtonArrayCollection
的 CFC,然后可能会扩展它到ActionItemCollection
,这样你就可以在集合上进行类型提示。 - AlexP