Casting data to type of variables stored in object[]

淺唱寂寞╮ 提交于 2020-01-05 04:56:06

问题


I am trying to emulate the way fortran reads data from text files in C#. In fortran you have something like

        READ(60,2005,ERR=9880,END=8000) A,B,C,D
  2005  FORMAT(I8,A20,2F10.3)

and A, B, C, D are automatically set to the correct type based on the format statement.

I have tried things along the lines of:

    private static void Example(string[] Data, ref object[] Variables)
    {
        for (int i = 0; i < Data.Length; i++)
            Variables[i] = (typeof(Variables[i]))Data;
    }

but can't even get code that will compile.

At the moment I'm assigning to the variables by passing out all the data in an object array, like this

    private static object[] Example(string[] Data)
    {
        object[] output = new object[Data.Length - 1];

        for (int i = 0; i < Data.Length; i++)
        {
            int dummyInt;
            if (int.TryParse(Data[i], out dummyInt))
                output[i] = dummyInt;
            /// Try to parse other possible data types
        }

        return output;
    }

    private static void UseExample()
    {
        object[] values = Example(new string[] { "     356", "Some text           ", "   956.365", "564050.201" });
        int A = (int)values[0];
        string B = (string)values[1];
        double C = (double)values[2];
        double D = (double)values[3];
    }

This is simplified, but is in essence what I am doing: determining the type of the data, casting to that type and passing all fields out as an object and then casting again when I assign to the variables that hold the data. Which requires knowing what variables will come out and also a lot of extra coding if there are lots of data fields.

I am looking for a way I can pass in all the variables that should be set and set them to the correct value value, but for that I need to be able to cast the data to the type of the appropriate variable.

Can this be done? If it is possible, how can it be done?

来源:https://stackoverflow.com/questions/13266305/casting-data-to-type-of-variables-stored-in-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!