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 []したがって、引数の前に記述する必要はありません。

以下のリンクも役立つと思い
ます

于 2012-04-10T10:29:49.273 に答える