简体   繁体   English

c#中的通用参数

[英]Generic parameter in c#

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 {

Set your method signature to be:将您的方法签名设置为:

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

and call it like:并称它为:

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

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来自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. params 关键字允许您指定一个方法参数,该参数采用可变编号 arguments。您可以发送参数声明中指定类型的逗号分隔列表 arguments,或指定类型的数组 arguments。 You also can send no arguments.您也可以发送 no arguments。

So you don't need to write new [] before arguments.所以arguments之前不需要写new []

I guess the link below will also be useful我想下面的链接也会有用
how-to-pass-a-single-object-to-a-params-object 如何将单个对象传递给参数对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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