2017-12-07 5 views
1

비어 있으면 기본값을 설정하는 방법. 그렇지 않은 경우 기본 문자열 (10,20)을 작성합니다.C 번호 : I 입력 문자열 경우</p> <pre><code>public void AddSomething(string ice = "10", string sweet = "20") { Console.Write(ice); Console.Write(sweet); } </code></pre> <p>그래서, 그것은 문자열을 작성합니다 :이 같은 방법이있는 경우 입력이

하지만이 같은 싶지 :

public void AddSomething(string ice = "10", string sweet = "20") 
{ 
    if(ice = "") 
     ice = default_vaule; //which is 10 
    if(sweet = "") 
     sweet = default_vaule; //which is 20 
    Console.Write(ice); 
    Console.Write(sweet); 
} 

때문에 사용자 입력 빈 문자열 "" 경우, 나는 사용자에게 기본 값을 작성할 수 있습니다, 그래서뿐만 아니라이 수행 할 수 있습니다

AddSomething("5"); 

두 가지 모두 :

AddSomething("5",""); 
AddSomething("","5"); 

누구나 어떻게 할 수 있는지 알고 있습니까? 고마워!

답변

1

그래서 당신은 자신을 반복하지 않고 런타임시 메소드 매개 변수의 디폴트 값을 얻으려면 다시 값을 입력하지 않고 (FE는 기본값을 변경하는 경우가 너무 거기를 변경 한 것을 방지 할 수 있도록 매개 변수의 값)?

defaultof(parameter) -operator가 없기 때문에 쉽지 않습니다 (nameof -operator와 유사). 리플렉션을 사용해야했습니다.

당신은이 확장 사용할 수

: 기본 값이 결정될 수있는 경우도 정보를 반환 할 수 있도록 단지 래퍼 인 다음 클래스의 인스턴스를 반환

public static class MethodExtensions 
{ 
    public static Result<T> ParameterDefault<T>(this MethodBase m, string paramName) 
    { 
     ParameterInfo parameter = m.GetParameters() 
      .FirstOrDefault(p => p.Name == paramName); 
     if (parameter == null) 
      throw new ArgumentException($"No parameter with given name '{paramName}' found", nameof(paramName)); 
     if (parameter.ParameterType != typeof(T)) 
      throw new ArgumentException($"Parametertype is not '{typeof(T)}' but '{parameter.ParameterType}'"); 

     if(parameter.HasDefaultValue) 
      return new Result<T>((T)parameter.DefaultValue, true); 
     else 
      return new Result<T>(default(T), false); 
    } 
} 

을 :

public class Result<T> 
{ 
    public Result(T value, bool success) 
    { 
     Value = value; 
     Success = success; 
    } 
    public T Value { get; private set; } 
    public bool Success { get; private set; } 
} 

는 이제 방법은 다음과 같습니다

public void AddSomething(string ice = "10", string sweet = "20") 
{ 
    MethodBase m = MethodBase.GetCurrentMethod(); 
    if (ice == "") 
     ice = m.ParameterDefault<string>(nameof(ice)).Value; 
    if (sweet == "") 
     sweet = m.ParameterDefault<string>(nameof(sweet)).Value; 
    Console.Write(ice); 
    Console.Write(sweet); 
} 

당신은 repea 할 필요가 없습니다 매개 변수 값.

+0

이 작업 중입니다! 내 C# 버전에서만 "nameof"를 지원하지 않습니다. 감사합니다. – DaveG

2

귀하는 이미 귀하의 질문에 답변하셨습니다. 널 케이스도 커버 할 수 있습니다.

public void AddSomething(string ice = "10", string sweet = "20") 
{ 
    if(string.IsNullOrEmpty(ice)) ice = "10"; 
    if(string.IsNullOrEmpty(sweet)) sweet = "20"; 
    Console.Write(ice); 
    Console.Write(sweet); 
} 

중복 리터럴을 쓰지 않으려면 상수를 사용할 수 있습니다.

// these are constant and can be used as default value for parameters. 
const string DefaultSweet = "20";  
const string DefaultIce = "10"; 

public void AddSomething(string ice = DefaultSweet, string sweet = DefaultIce) 
{ 
    if(string.IsNullOrEmpty(ice)) ice = DefaultIce; 
    if(string.IsNullOrEmpty(sweet)) sweet = DefaultSweet; 
    Console.Write(ice); 
    Console.Write(sweet); 
} 

보조 노트 : string.IsNullOrEmpty(ice)ice == "" || ice == null

+0

그는 다시 제공하지 않고 런타임에이 기본값에 액세스하려고합니다.'nameof (ice)'와 같이 매개 변수의 이름을 반환하는'nameof' 연산자와 비슷하게 그는'defaultof (ice)'를 원합니다. 너 자신을 반복해야 해. –

+0

또는 그 이상 : string.IsNullOrEmpty() – Fortega

+0

제안에 감사드립니다. –

0

(적어도 나를 위해)이 질문에 해당 불분명하지만 당신이 게시 한 내가 이런 솔루션을 제안 할 수 있습니다에서 :

// default value for "ice" 
const string default_ice = "10"; 
// default value for "sweet" 
const string default_sweet = "20"; 

public void AddSomething(string ice = default_ice, string sweet = default_sweet) 
{ 

    // check if "ice" value is set 
    if(string.IsNullOrEmpty(ice)) 
     ice = default_ice; // set "ice" value to the default one 

    // check if "sweet" value is set 
    if(string.IsNullOrEmpty(sweet)) 
     sweet = default_sweet; // set "sweet" value to the default one 

    Console.Write(ice); 
    Console.Write(sweet); 
} 

을 다음과 같이 호출 할 수도 있습니다.

AddSomething(sweet: "1337"); 
// or 
AddSomething("13", "37"); 

요 좋아.

Try this online

관련 문제