Dan*_* T. 11 c# coldfusion static coldfusion-9
在C#中,我创建了静态方法来帮助我执行简单的操作.例如:
public static class StringHelper
{
public static string Reverse(string input)
{
// reverse string
return reversedInput;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在控制器中,我会通过简单地使用:
StringHelper.Reverse(input);
Run Code Online (Sandbox Code Playgroud)
现在我正在使用ColdFusion和Model Glue,我想做同样的事情.但是,似乎ColdFusion中没有静态方法的概念.如果我像这样创建一个CFC:
component StringHelper
{
public string function Reverse(string input)
{
// reverse string
return reversedInput;
}
}
Run Code Online (Sandbox Code Playgroud)
我是否可以通过StringHelper在控制器中创建实例来调用此方法,如下所示:
component Controller
{
public void function Reverse()
{
var input = event.getValue("input");
var stringHelper = new StringHelper();
var reversedString = stringHelper.Reverse(input);
event.setValue("reversedstring", reversedString);
}
}
Run Code Online (Sandbox Code Playgroud)
或者在某些地方我可以放置"静态"CFC,框架将在后台创建一个实例,这样我就可以使用它,好像它是静态的,有点像helpers文件夹的工作方式?
Jas*_*ean 16
不,你是对的,ColdFusion中没有静态方法的概念.我认为大多数人会通过在应用程序启动时使用应用程序范围中的单例实用程序来解决此问题.因此,在onApplication的App.cfc中,您可能会:
<cfset application.StringHelper = createObject("component", "path.to.StringHelper") />
Run Code Online (Sandbox Code Playgroud)
然后,当您需要从任何地方调用它时,您将使用:
<cfset reversedString = application.StringHelper.reverse(string) />
Run Code Online (Sandbox Code Playgroud)
是的,它不像静态方法那么干净.也许总有一天我们会有像他们这样的东西.但是现在我觉得这和你会得到的一样接近.
在ColdFuison中创建静态的一种方法是将函数或变量放在对象的元数据中.它不完美,但像静态一样,你不必创建一个对象的实例来调用它们,它们将持续到服务器重新启动,所以它们在第一次调用后非常快.
这是一个快速片段:
component name="Employee"
{
public Employee function Init(){
var metadata = getComponentMetaData("Employee");
if(!structKeyExists(metadata,"myStaticVar")){
lock name="metadata.myStaticVar" timeout="10"{
metadata.myStaticVar = "Hello Static Variable.";
}
}
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
更多细节:http://blog.bittersweetryan.com/2011/02/using-metadata-to-add-static-variables.html.