[C#] Class 의 string 프로퍼티 값의 NULL 문자열 제거

2014. 6. 20. 13:29Coders

안녕하세요.

오늘 뭐 좀 하다가 필요해서 만들었는데, 유용하리라 보고 포스팅 합니다.

예전에 올렸던 글 "C# 프로퍼티 값을 세팅하자." 가 연장되는 이야기 이긴 합니다만, 어쨌거나.


특정 클래스(거의 구조체 입니다만)를 XML 로 Serialize 하는 작업을 하는데요, 해당 클래스의 String 타입 프로퍼티 중, 문자열 중간에 널(\0) 문자열이 들어가는 바람에 Serialize 가 실패하는 경우가 발생하여, 이걸 일일이 찾기도 어렵고 해서, 메서드를 만들었어요.


특정 클래스에서 프로퍼티 목록을 뽑아내어, 그 중, 데이터 타입이 string 이면서, getter, setter 를 모두 지원하면, null 문자를 제거해 주는 메서드 입니다.


간단한(작동하는) 소스 입니다.

private void RemoveNullString(object obj)
{
	System.Reflection.PropertyInfo[] propInfos = obj.GetType().GetProperties();

	foreach (System.Reflection.PropertyInfo pInfo in propInfos)
	{
		if (pInfo != null && pInfo.DeclaringType == typeof(string))
		{
			System.Reflection.MethodInfo getMethod = pInfo.GetGetMethod();
			System.Reflection.MethodInfo setMethod = pInfo.GetSetMethod();

			if (getMethod != null && setMethod != null)
			{
				string beforeValue = getMethod.Invoke(obj, null) as string;

				if (beforeValue != null && beforeValue.Contains("\0"))
				{
					setMethod.Invoke(obj,
						new object[] { beforeValue.Replace("\0", string.Empty) });
				}
			}
		}
	}
}