从C++/CLI到C#的函数

本文关键字:函数 CLI C++ | 更新日期: 2023-09-27 18:20:17

我想将此代码从C++转换为C#:

array<String^,2>^ SelectARows(String^ myConnectionString, String^ inlist) 
{
PrintToErrorFile("Entering SelectARows...");
array<String^,2>^ names = gcnew array<String^,2>(1200,4);
try{
    OleDbConnection^ myConnection = gcnew OleDbConnection(myConnectionString);
    size_t found;
    found=myConnectionString->IndexOf("PIOLEDB");
    int pifound = 0;
    if (found!=string::npos){
    pifound = int(found);
    }
    String^ mySelectQuery;
    if(pifound > 0){
        mySelectQuery = "select tag, time, value, status FROM piarchive..pisnapshot WHERE tag in (" + inlist +")";
}

PrintToErrorFile是我创建的另一个函数,我对这个Visual C++不太熟悉,任何帮助都会很棒:)

从C++/CLI到C#的函数

只有数组语法应该成为绊脚石。这是C#版本:

string[,] names = new string[1200,4];
string[,] SelectARows(string myConnectionString, string inlist) 
{
    PrintToErrorFile("Entering SelectARows...");
    string[,] names = new string[1200,4];
    // I don't know what your intent is for myConnection, as you didn't finish your
    // try block, but it will be autodisposed by the using block.  Maybe this isn't your
    // intent, but no matter what myConnect should be disposed since it implements
    // IDisposable
    using(OleDbConnection myConnection = new OleDbConnection(myConnectionString)) {
        // technically, this should be >= 0, but I'm going from  your code
        bool found = myConnectionString.IndexOf("PIOLEDB") > 0;
        string mySelectQuery = null;
        if(found)
            mySelectQuery = "select tag, time, value, status FROM piarchive..pisnapshot WHERE tag in (" + inlist +")";
        // at this point mySelectQuery is either null or the query string.
        // honestly, I would prefer this form, which is equivalent
        string mySelectQuery = found ? "select tag, time, value, status FROM piarchive..pisnapshot WHERE tag in (" + inlist +")"
                                     : null;
    }
}

您可以尝试在C++/CLI中编译代码,然后在打开C#的情况下使用.NET反射器查看代码,以开始操作。