반응형

보통 C#에서 제공하는 class에서는 여러가지 유용한 함수들을 제공하고 있지만 해당 object를 이용하여 값을 체크한다던가 한다면 따로 함수를 만들어서 파라미터로 해당 object를 넘겨서 체크해줘야 한다.

그런 경우 코드 가독성이 좋지 않기 때문에 이경우 Extension Method 를 생성하여 편리하게 사용이 가능하다.

  • string에서 마지막 문제 제거
string test = "123456";
test = test.Substring(0, test.Length - 1);
  • Extension Method 정의후 사용시
public static string RemoveLastCharacter(this String instr)
{
	return instr.Substring(0, instr.Length - 1);
}
string test = "123456";
test = test.RemoveLastCharacter();

 

번거롭고 별거 아닐수도 있지만 코드양이 많아지다보면 코드 가독성에 큰 영향이 있다.

 

  • String Extenstion Class
public static class StringExtension
{
	public static bool HasValue(this string source)
	{
		return string.IsNullOrEmpty(source) == false;
	}

	public static bool IsNullOrEmpty(this string source)
	{
		return string.IsNullOrEmpty(source);
	}

	public static string Reverse(this string input)
	{
		char[] chars = input.ToCharArray();
		Array.Reverse(chars);
		return new String(chars);
	}

	public static string RemoveLastCharacter(this String instr)
	{
		return instr.Substring(0, instr.Length - 1);
	}

	public static string RemoveLast(this String instr, int number)
	{
		return instr.Substring(0, instr.Length - number);
	}

	public static string RemoveFirstCharacter(this String instr)
	{
		return instr.Substring(1);
	}

	public static string RemoveFirst(this String instr, int number)
	{
		return instr.Substring(number);
	}

	public static string F(this string s, params object[] args)
	{
		return string.Format(s, args);
	}

	/// <summary>
	/// Parses a string into an Enum
	/// </summary>
	/// <typeparam name="T">The type of the Enum</typeparam>
	/// <param name="value">String value to parse</param>
	/// <returns>The Enum corresponding to the stringExtensions</returns>
	public static T EnumParse<T>(this string value)
	{
		return EnumParse<T>(value, false);
	}

	/// <summary>
	/// Example : TestEnum foo = "Test".EnumParse<TestEnum>();
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <param name="value"></param>
	/// <param name="ignorecase"></param>
	/// <returns></returns>
	public static T EnumParse<T>(this string value, bool ignorecase)
	{

		if (value == null)
		{
			throw new ArgumentNullException("value");
		}

		value = value.Trim();

		if (value.Length == 0)
		{
			throw new ArgumentException("Must specify valid information for parsing in the string.", "value");
		}

		Type t = typeof(T);

		if (!t.IsEnum)
		{
			throw new ArgumentException("Type provided must be an Enum.", "T");
		}

		return (T)Enum.Parse(t, value, ignorecase);
	}


	public static int ToInt(this String input, int defaultValue = 0)
	{
		int result;

		if (!int.TryParse(input, out result))
		{
			result = defaultValue;
		}

		return result;
	}

	/// <summary>
	/// MessageBox.Show(s.IfNullElse("Null Alternate Value"));
	/// </summary>
	/// <param name="input">string to check</param>
	/// <param name="nullAlternateValue">value to be returned in case string is null</param>
	/// <returns>string: original or null alternative value</returns>
	public static string IfNullElse(this string input, string nullAlternateValue)
	{
		return (!string.IsNullOrWhiteSpace(input)) ? input : nullAlternateValue;
	}

	/// <summary>
	/// string value = "abc";
	/// bool isnumeric = value.IsNumeric();// Will return false;
	/// </summary>
	/// <param name="theValue"></param>
	/// <returns></returns>
	public static bool IsNumeric(this string theValue)
	{
		long retNum;
		return long.TryParse(theValue, System.Globalization.NumberStyles.Integer, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
	}
}

 

여러가지 다양한 Extension Method 모음 싸이트

extensionmethod.net/

 

Recently Added Extension Methods - ExtensionMethod.NET

©2007-2021 ExtensionMethod.NET. ExtensionMethod.NET was built by Loek van den Ouweland and Fons Sonnemans with ASP.NET Core, HTML, CSS, Javascript, SQL Server and some of the great methods you have posted here. By using this website, you agree to the lega

extensionmethod.net

 

반응형

'[====== Development ======] > C#' 카테고리의 다른 글

.Net용 Json 라이브러리  (0) 2021.01.07
REST API 사용  (1) 2021.01.07
간단한 Logger 만들기  (0) 2021.01.07
C# Expression  (0) 2021.01.04
WPF/C# 에서 이미지파일 인쇄 하기  (0) 2020.11.16

+ Recent posts