在 class 中声明、更新和访问 System::String

Declaring, updating and accessing a System::String within a class

我从昨天开始就一直在搜索我的问题,但到目前为止我没有找到任何相关内容。顺便说一句,我对 classes 很陌生,所以请多关照。

我在 class 中声明了一个 System::String 变量,我创建了一个方法来更新该变量和另一个 return 它的值。但是,更新所述变量会引发异常。在 class 中声明 System::String 的正确方法是什么?如何更新 return 它是 class 中的值?

异常:

A first chance exception of type 'System.NullReferenceException' occurred in XXX.exe

这是我制作的 class 的简化版本:

ref class clTimeStamp {
public:
    clTimeStamp()
    {
        strDatestamp = gcnew System::String("");
    }
private:
    System::String ^strDatestamp;
public:
    void SetDateStamp(System::String ^a)
    {
        strDatestamp = a->Substring( 6, 4 );    // yyyy
        strDatestamp = strDatestamp + "-" + a->Substring( 3, 2 );
        strDatestamp = strDatestamp + "-" + a->Substring( 0, 2 ) + "T";
    }
    System::String ^GetDateTimeStamp()
    {
        return strDatestamp;
    }
};

这就是我在主程序中使用它的方式:

strBuffer = gcnew String(buffer.c_str());
clTimeStampHSCAN1->SetDateStamp(strBuffer);
fprintf(handle, "%s\n", clTimeStampHSCAN1->GetDateTimeStamp());

我真的对 C++-CLI 中的字符串感到困惑,创建它们的方法太多了,而且变得非常复杂。

非常感谢您的帮助。

编辑:根据 Caninonos 的建议进行了更新(更改构造函数中 String 变量的初始化),但结果仍然相同。

我认为问题不在您 post 编辑的代码中,而是在省略的代码中。在调用SetDateStamp()成员函数之前,必须用gcnew分配的clTimeStamp对象初始化clTimeStampHSCAN1指针。这是一个对我有用的例子。

// so_string.cpp : main project file.

#include "stdafx.h"
#include <string>

using namespace System;

ref class clTimeStamp {
public:
    clTimeStamp()
    {
        strDatestamp = nullptr;
    }
private:
    System::String ^strDatestamp;
public:
    void SetDateStamp(System::String ^a)
    {
        strDatestamp = a->Substring( 6, 4 );    // yyyy
        strDatestamp = strDatestamp + "-" + a->Substring( 3, 2 );
        strDatestamp = strDatestamp + "-" + a->Substring( 0, 2 ) + "T";
    }
    System::String ^GetDateTimeStamp()
    {
        return strDatestamp;
    }
};


int main(array<System::String ^> ^args)
{
    // This is unmanaged C++
    std::string buffer("01/15/2016 23:00");
    FILE *handle = fopen ("c:\temp\myfile.txt" , "w");

    // These are .NET managed objects
    String ^strBuffer = gcnew String(buffer.c_str());
    clTimeStamp ^clTimeStampHSCAN1 = gcnew clTimeStamp();

    clTimeStampHSCAN1->SetDateStamp(strBuffer);
    fprintf(handle, "%s\n", clTimeStampHSCAN1->GetDateTimeStamp());
    return 0;
}

注意:我真的很想清理这段代码,但我决定保持它与原始示例基本相同。未来值得研究的一些事情是一致的命名和输入验证。 C++-CLI 允许从高级 .Net 管理到接近硬件的低级 C 风格函数的不同级别的抽象。你有一点两者混合在一起。我不会深入探讨这个问题,因为这不是问题,而且这不是博客 post。