问题描述
在 C# 中,我创建了静态方法来帮助我执行简单的操作.例如:
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;
}
}
然后在控制器中,我会通过简单地使用来调用它:
Then in a controller, I would call it by simply using:
StringHelper.Reverse(input);
现在我将 ColdFusion 与 Model Glue 一起使用,我想做同样的事情.但是,ColdFusion 中似乎没有静态方法的概念.如果我这样创建 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;
}
}
我只能通过在控制器中创建 StringHelper
的实例来调用此方法吗,如下所示:
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);
}
}
或者是否有一些地方可以放置框架将在幕后创建一个实例的静态"CFC,这样我就可以像静态一样使用它,有点像 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?
推荐答案
不,你是对的,ColdFusion 中没有静态方法的概念.我认为大多数人会通过在应用程序启动时创建的应用程序范围内使用单例实用程序来解决这个问题.所以在你的 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") />
然后当你需要从任何你会使用的地方调用它时:
Then when you needed to call it from anywhere you would use:
<cfset reversedString = application.StringHelper.reverse(string) />
是的,它不像静态方法那样干净.也许有一天我们可以拥有类似的东西.但现在我认为这是你将得到的最接近的.
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.
这篇关于ColdFusion 中静态方法的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!