2025년 2월 24일 월요일

c# 클래스 멤버 출력

c#으로 작업할때 VO클래스 멤버 필드와 프로퍼티를 출력 해야할일이 있다.

이때는 Reflection을 이용해서 출력하면 되는데 하나하나 하기 귀찮으면

MemberPrintAble 클래스를 만들어서 상속시키면 된다.


public abstract class MemberPrintAble
{
    public string MemberString()
    {
        FieldInfo[] fieldInfos = this.GetType().GetFields();
        PropertyInfo[] propertyInfos = this.GetType().GetProperties();
        //
        var sb = new StringBuilder();
        foreach (var ffo in fieldInfos)
        {
            var value = ffo.GetValue(this) ?? "(빈값)";
            sb.AppendLine(ffo.Name + ": " + value.ToString());
        }
        foreach (var info in propertyInfos)
        {
            var value = info.GetValue(this, null) ?? "(빈값)";
            sb.AppendLine(info.Name + ": " + value.ToString());
        }
        return sb.ToString();
    }
}



요로코롬 정의해놓고 MemberPrintAble클래스를 상속하고 

사용할때 MemberString 메서드를 호출하면

멤버필드와 프로퍼티값을 출력할수 있다.

ToString으로 override해서 언제하고 있뉘??



댓글 없음:

댓글 쓰기