2

我有这个课程:

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[]
  }
}

有没有办法做到这一点而不铸造?

像:

class SendInfo {
    static public f_WriteInfo(params T _info) where T : Info {
4

4 回答 4

11

将您的方法签名设置为:

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

并称之为:

SendInfo.f_WriteInfo(new AInfo(){ ... }, new BInfo(){ ... });
于 2012-04-10T08:55:57.773 回答
4

这很好用

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());
    }
}
于 2012-04-10T09:03:01.017 回答
2

尝试:

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()
                   } );
    }
}

}

于 2012-04-10T08:56:58.383 回答
1

来自MSDN

params 关键字允许您指定一个方法参数,该参数采用可变数量的参数。您可以发送以逗号分隔的参数声明中指定类型的参数列表,或指定类型的参数数组。您也可以不发送任何参数。

所以你不需要new []在参数之前写。

我想下面的链接也将很有用
how-to-pass-a-single-object-to-a-params-object

于 2012-04-10T10:29:49.273 回答