問題描述
在 C# 中,我創(chuàng)建了靜態(tài)方法來幫助我執(zhí)行簡(jiǎn)單的操作.例如:
In C#, I created static methods to help me perform simple operations. For example:
public static class StringHelper
{
public static string Reverse(string input)
{
// reverse string
return reversedInput;
}
}
然后在控制器中,我會(huì)通過簡(jiǎn)單地使用來調(diào)用它:
Then in a controller, I would call it by simply using:
StringHelper.Reverse(input);
現(xiàn)在我將 ColdFusion 與 Model Glue 一起使用,我想做同樣的事情.但是,ColdFusion 中似乎沒有靜態(tài)方法的概念.如果我這樣創(chuàng)建 CFC:
Now I'm using ColdFusion with Model Glue, and I'd like to do the same thing. However, it seems like there's no concept of static methods in ColdFusion. If I create a CFC like this:
component StringHelper
{
public string function Reverse(string input)
{
// reverse string
return reversedInput;
}
}
我只能通過在控制器中創(chuàng)建 StringHelper
的實(shí)例來調(diào)用此方法嗎,如下所示:
Can I only call this method by creating an instance of StringHelper
in the controller, like this:
component Controller
{
public void function Reverse()
{
var input = event.getValue("input");
var stringHelper = new StringHelper();
var reversedString = stringHelper.Reverse(input);
event.setValue("reversedstring", reversedString);
}
}
或者是否有一些地方可以放置框架將在幕后創(chuàng)建一個(gè)實(shí)例的靜態(tài)"CFC,這樣我就可以像靜態(tài)一樣使用它,有點(diǎn)像 helpers 文件夾的工作原理?
Or is there some place where I can put 'static' CFCs that the framework will create an instance of behind the scenes so I can use it as if it was static, kind of like how the helpers folder works?
推薦答案
不,你是對(duì)的,ColdFusion 中沒有靜態(tài)方法的概念.我認(rèn)為大多數(shù)人會(huì)通過在應(yīng)用程序啟動(dòng)時(shí)創(chuàng)建的應(yīng)用程序范圍內(nèi)使用單例實(shí)用程序來解決這個(gè)問題.所以在你的 App.cfc 中 onApplication 開始你可能有:
Nope, you are correct, there is no concept of static methods in ColdFusion. I think most would solve this problem through the use a singleton utilities in the application scope that are create when the application starts. So in your App.cfc in onApplication start you might have:
<cfset application.StringHelper = createObject("component", "path.to.StringHelper") />
然后當(dāng)你需要從任何你會(huì)使用的地方調(diào)用它時(shí):
Then when you needed to call it from anywhere you would use:
<cfset reversedString = application.StringHelper.reverse(string) />
是的,它不像靜態(tài)方法那樣干凈.也許有一天我們可以擁有類似的東西.但現(xiàn)在我認(rèn)為這是你將得到的最接近的.
Yeah, it's not as clean as static methods. Maybe someday we could have something like them. But right now I think this is as close as you will get.
這篇關(guān)于ColdFusion 中靜態(tài)方法的等價(jià)物是什么?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!