2012-08-06 2 views
1

해당 클래스의 속성에서 클래스 메서드를 호출하는 방법을 알아 내려고하고 있습니다. 다음은 두 클래스입니다.해당 클래스의 속성에서 클래스 메서드를 호출하는 방법

public class MrBase 
{ 
    public int? Id { get; set; } 
    public String Description { get; set; } 
    public int? DisplayOrder { get; set; } 

    public String NullIfEmpty() 
    { 
     if (this.ToString().Trim().Equals(String.Empty)) 
      return null; 
     return this.ToString().Trim(); 
    } 
} 

public class MrResult : MrBase 
{ 
    public String Owner { get; set; } 
    public String Status { get; set; } 

    public MrResult() {} 
} 

MrResult는 MrBase에서 상속됩니다.

지금, 그래서처럼 ... 이러한 클래스의 속성 중 하나에 NullIfEmpty 메소드를 호출 할 수 있도록하려면 :

MrResult r = new MrResult(); 
r.Description = ""; 
r.Description.NullIfEmpty(); 
r.Owner = "Eric"; 
r.Owner.NullIfEmpty(); 

감사합니다.

에릭

+0

'소유자'는 문자열입니다. 대신에'r.NullIfEmpty()'를 호출해야합니다. –

+1

왜이 목적을위한 확장 메서드를 만드는 것이 좋을까요? – jsmith

+1

또는 확장 메서드를 사용할 수 있습니다. (http://msdn.microsoft.com/en-us/library/bb383977.aspx) – xbonez

답변

2

당신은 string에 대한 확장 메서드를 작성해야 :

public static class StringExtensions 
{ 
    public static string NullIfEmpty(this string theString) 
    { 
     if (string.IsNullOrEmpty(theString)) 
     { 
      return null; 
     } 

     return theString; 
    } 
} 

사용법 : 당신의 주요 목표는 자동으로 각 클래스 string 속성을 "수정"하는 경우

string modifiedString = r.Description.NullIfEmpty(); 

, 당신은 반사를 사용하여 이것을 달성 할 수 있습니다. 여기에 기본 예제 :

private static void Main(string[] args) 
{ 
    MrResult r = new MrResult 
    { 
     Owner = string.Empty, 
     Description = string.Empty 
    }; 

    foreach (var property in r.GetType().GetProperties()) 
    { 
     if (property.PropertyType == typeof(string) && property.CanWrite) 
     { 
      string propertyValueAsString = (string)property.GetValue(r, null); 
      property.SetValue(r, propertyValueAsString.NullIfEmpty(), null); 
     } 
    } 

    Console.ReadKey(); 
} 
+2

나는 똑같은 대답을하고 싶습니다. 그러나'MrBase'의 속성뿐만 아니라 * 문자열에 * NullIfEmpty를 할 수 있다는 것을 기억하십시오. –

+0

@ 뮤두 (Mudu) 확장은 아마도 다른 곳에서도 유용 할 수있을 정도로 일반적 일 것이다. – James

+0

그리고 MrBase와 동일한 네임 스페이스에서 Extensions 클래스를 internal로 제한 할 수 있습니다. –

3

이 코드는 예를 들어, 당신의 NullIfEmpty 방법에 약간의 수정으로 세터로를 내장 할 수 다음 모델을 구체적으로하려면

private String _owner; 

public String Owner 
{ 
    get { return _owner; } 
    set { _owner = NullIfEmpty(value); } 
} 

... 
public String NullIfEmpty(string str) 
{ 
    return str == String.Empty ? null : str; 
} 
+0

+1은 소비자가 매번 NullIfEmpty를 호출 할 필요가 없기 때문에 인터페이스가 더 안전해진 것처럼 보입니다 (어쨌든 나는 생각합니다.). –

+0

이것은 문자열을 자르지 않거나 asker의 예제 코드처럼'' "''와 똑같이 취급하지 않음에 유의하십시오. 적절하게 수정해야 할 수도 있습니다. 트리밍 대신'string.IsNullOrWhitespace'를보고 비어 있는지 확인하는 것이 좋습니다. –

+0

@Mudu 예 속성이 설정되면 자동으로 값이 호출됩니다. 단점은 모든 속성에서 동일한 getter를 구현해야한다는 것입니다. 그러나, OP가 리플렉션을 사용하기를 원하지 않는 한, 나는이 사실을 알지 못합니다. – James