简体   繁体   中英

Unable to build an array from a class in Xamarin.Forms with C#

I'm working on a Xamarin.Forms project with C# to connect to an OPC server and read values. I'm able to read the values, but I'm having trouble collating them into a list or array. After I do, I'd like to convert the values to ASCII.

Below is the code that is passed;

var readRequest = new ReadRequest
{
    // set the NodesToRead to an array of ReadValueIds.
    NodesToRead = new[] {
    // construct a ReadValueId from a NodeId and AttributeId.
    new ReadValueId {
        // you can parse the nodeId from a string.
        // e.g. NodeId.Parse("ns=2;s=Demo.Static.Scalar.Double")
        NodeId = NodeId.Parse("ns=2;s=Link_CatConHybrid.2D.InStr1"),

        //NodeId.Parse(VariableIds.Server_ServerStatus),
        // variable class nodes have a Value attribute.
        AttributeId = AttributeIds.Value
    },

    new ReadValueId
    {
        NodeId = NodeId.Parse("ns=2;s=Link_CatConHybrid.2D.InStr2"),
        AttributeId = AttributeIds.Value
    }
}

};
// send the ReadRequest to the server.
var readResult = await channel.ReadAsync(readRequest);

// DataValue is a class containing value, timestamps and status code.
// the 'Results' array returns DataValues, one for every ReadValueId.

DataValue dvr = readResult.Results[0];
DataValue dvr2 = readResult.Results[1];

Console.WriteLine("The value of Instr1 is {0}, InStr2 is {1}", dvr.Variant.Value, dvr2.Variant.Value);

What am I doing wrong or overlooking?

Edit: How would I combine all of the readResults into one ?

读取结果

Just create a DataValue list and store them. Try like:

List<DataValue> endResult = new List<DataValue>();
foreach (DataValue  value in readResult.Results)
{
    endResult.Add(value);
}

Since Results is alerady collection of DataValue, you can just say

var dataValueCollection = readResult.Results; // if you want return collection you can just say return readResult.Results

If you are trying to write the values to console, then you can have loop directly on readResult.Results as below:

foreach(var dv in readResult.Results)
{
    Console.WriteLine("The Value of InStr = {0}", dv.Variant.Value);
    Console.WriteLine("The Value of InStr = {0}", dv.Variant.ReadValueId); // This line shows how to access ReadValueId.
    // You can access other properties same as above
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM