C++CLI 如何使用许多其他类可访问的方法创建实用程序类



我有许多类使用相同的泛型函数/方法。目前,我已经为每个类编写了这些方法,但这涉及不必要的重复。因此,我想将这些方法移动到一个 Utils 类中,该类可由所有需要使用这些方法的类访问。我认为这可以通过GenericTemplate来完成,但我没有可以理解的例子。

这就是我现在所做的(省略所有非必需品):

基因组.h:

ref class Genome
{
public:
    List<wchar_t>^ stringToList(String^ inString);  // convert string to List with  chars
};

基因组.cpp:

List<wchar_t>^ Genome::stringToList (String^ inString)
{
    List<wchar_t>^ tmpList = gcnew List<wchar_t>(); 
    int i;
    for (i = 0; i < inString->Length; i++)
        tmpList->Add(inString[i]);
    return tmpList;
}

典型的方法调用如下所示:

cString->AddRange(stringToList(aLine)); // genome string is stored as one line

其中 cString 的类型为 List<wchar_t>^

因此,如果我将stringToList方法移动到Utils.hUtils.cpp类,代码会是什么样子,以及如何在类 Genome.cpp 和其他类中调用这个和其他 Utils 方法?

谢谢,一月

我将实用程序函数放在一个标记为抽象密封的类中。由于类是抽象密封的,因此无法创建它的实例,因此必须将所有成员声明为静态。结果相当于拥有自由函数。

例如,在标题中,您将拥有

public ref class MyUtils abstract sealed
{
    // ........................................................................
    private:
        static MyUtils ();
    public:
        static System::Double CalculateAverage  ( cli::array<System::Double>^ arrayIn );

};

在.cpp

MyUtils::MyUtils ()
{
}

System::Double MyUtils::CalculateAverage ( cli::array<System::Double>^ arrayIn )
{
    // the code doing the calculation...
}

调用此方法就像调用任何静态方法一样

例如

cli::array<System::Double>^ values = gcnew cli::array<System::Double>(5);
    // ...
    // put some data in the array
    // ...
System::Double average = MyUtils::CalculateAverage ( values );

当然,您也可以将泛型方法作为此类的成员。

最新更新