program story

C # 4.0, 선택적 매개 변수 및 매개 변수가 함께 작동하지 않음

inputbox 2020. 12. 9. 08:09
반응형

C # 4.0, 선택적 매개 변수 및 매개 변수가 함께 작동하지 않음


선택적 매개 변수와 매개 변수가 함께있는 메소드를 어떻게 만들 수 있습니까?

static void Main(string[] args)
{

    TestOptional("A",C: "D", "E");//this will not build
    TestOptional("A",C: "D"); //this does work , but i can only set 1 param
    Console.ReadLine();
}

public static void TestOptional(string A, int B = 0, params string[] C)
{
    Console.WriteLine(A);
    Console.WriteLine(B);
    Console.WriteLine(C.Count());
}   

현재 유일한 옵션은 TestOptional을 오버로드하는 것입니다 (C # 4 이전에했던 것처럼). 선호되지는 않지만 사용 시점에서 코드를 정리합니다.

public static void TestOptional(string A, params string[] C)
{
    TestOptional(A, 0, C);
}

public static void TestOptional(string A, int B, params string[] C)
{
    Console.WriteLine(A);
    Console.WriteLine(B);
    Console.WriteLine(C.Count());
}

시험

TestOptional("A", C: new []{ "D", "E"});

이것은 나를 위해 일했습니다.

    static void Main(string[] args) {

        TestOptional("A");
        TestOptional("A", 1);
        TestOptional("A", 2, "C1", "C2", "C3"); 

        TestOptional("A", B:2); 
        TestOptional("A", C: new [] {"C1", "C2", "C3"}); 

        Console.ReadLine();
    }

    public static void TestOptional(string A, int B = 0, params string[] C) {
        Console.WriteLine("A: " + A);
        Console.WriteLine("B: " + B);
        Console.WriteLine("C: " + C.Length);
        Console.WriteLine();
    }

참고 URL : https://stackoverflow.com/questions/3948971/c-sharp-4-0-optional-parameters-and-params-do-not-work-together

반응형