Function to get an array of arbitrary type in C #

I created a function that processes an array of objects, a process (Object []). It works with any type, including integers and floats, if you put each element first. I would like the function to also accept unboxed elements, but only to place it immediately before processing. How to do it?

I could wrap several functions like process (int []) and process (float []), but this also seems to be troublesome. I tried the process (ValueType []), but the compiler still selects the process (Object []).

I have C # 2.0, but if there is a good solution for 3.0, I would like to see it.

+3
source share
5 answers

Short answer: you cannot (usefully) do this. Generics may seem capable of this, but as soon as you actually use a typed instance, you will pass it to the methods that the class object should take, so it will be put into the box (which is worse: it will be in the box many times, probably depending from your code).

If you want to improve performance by avoiding boxing in general, you will need to work on how you process these instances and ensure that all processing can be done in a safe way, despite the general approach - and this is not easy (see Generic Numerics ) in depends heavily on the processing you need to do.

0
source

? :

void ProcessArray<T>(T[] data)

" " - .

, , , . , , , : " ". , :)

, , .

+3
 static void T(Array a)
    {
        if (a is int[])
            Console.WriteLine("Int");
        else
            if (a is float[])
                Console.WriteLine("Float");
            else
                ....

    }
    static void Main(){
        T(new int[]{30});
        float[] a = { 11 };
        T(a);
    }
0

. :

using System;

namespace MyProg
{
  class Program
  {

    private static void ParamTest(params object[] args)
    {
      foreach (object o in args)
      {
        Console.Write(o);
        Console.WriteLine(", ");
      }
      Console.WriteLine();
    }

    static void Main(string[] args)
    {
      ParamTest(1, "abc", 2.4, new object());
    }
  }
}

1,
abc,
2.4,
System.Object,

!

0

, , . , , . , .

, . TypedReference #.

public void Process(__arglist)
{
    var iterator = new ArgIterator(__arglist);
    do
    {
        TypedReference typedReference = iterator.GetNextArg();
        Type type = __reftype(typedReference);
        if (type == typeof(int))
        {
            int value = __refvalue( typedReference,int);
            // value is an int
        }
        else if (type == typeof(string))
        {
            string value = __refvalue( typedReference,string);
            // value is a string
        }
        else if (type == typeof(double))
        {
            double value = __refvalue( typedReference,double);
            // value is a double
        }
        // etc.
    }
    while (iterator.GetRemainingCount() > 0);
}

:

Process(__arglist(45, "lol", 42.5));

. , , , ...

0
source

Source: https://habr.com/ru/post/1716882/


All Articles