Question

I have this classes:

interface Info{}

class AInfo : Info { }
class BInfo : Info { }

class SendInfo {
    static public f_WriteInfo(params Info[] _info) {

    }
}

class Test {
  static void Main() {
    SendInfo.f_WriteInfo( 
                        new[] { 
                            new AInfo(){ ... },
                            new BInfo(){ ... },
                       } );
// This will generate an error. 
// There will be need casting between new and [] like new Info[]
  }
}

Is there any way to do this without casting?

Like:

class SendInfo {
    static public f_WriteInfo(params T _info) where T : Info {
Était-ce utile?

La solution

Set your method signature to be:

static public f_WriteInfo(params Info[] _info) {}

and call it like:

SendInfo.f_WriteInfo(new AInfo(){ ... }, new BInfo(){ ... });

Autres conseils

this works fine

interface Info { }

class AInfo : Info { }
class BInfo : Info { }

class SendInfo
{
    public static void f_WriteInfo(params Info[] _info)
    {
    }
}

class Test
{
    static void Main()
    {
        SendInfo.f_WriteInfo(new AInfo(), new BInfo());
    }
}

try:

namespace ConsoleApplication1
{
    interface Info{}

public class AInfo : Info
{
    public AInfo(){}
}
public class BInfo : Info { }

class SendInfo {
    public static void f_WriteInfo(params Info[] _info) {

    }
}


class Program
{
    static void Main(string[] args)
    {
        SendInfo.f_WriteInfo( 
                    new Info[] { 
                        new AInfo(),
                        new BInfo()
                   } );
    }
}

}

From MSDN

The params keyword lets you specify a method parameter that takes a variable number of arguments. You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments.

So you don't need to write new [] before arguments.

I guess the link below will also be useful
how-to-pass-a-single-object-to-a-params-object

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top