code

구문 분석을 사용하여 문자열을 모든 유형으로 변환하는 일반 Parse () 함수가 있습니까?

codestyles 2020. 10. 12. 07:32
반응형

구문 분석을 사용하여 문자열을 모든 유형으로 변환하는 일반 Parse () 함수가 있습니까?


문자열을 제네릭 반환 형식 과 같은 int또는 date또는 long기반으로 제네릭 형식으로 변환하고 싶습니다 .

기본적으로 이와 같은 함수 Parse<T>(String)는 유형의 항목을 반환합니다 T.

예를 들어 int가 전달 된 경우 함수는 int.parse내부적으로 수행해야합니다 .


System.Convert.ChangeType

귀하의 예에 따라 다음을 수행 할 수 있습니다.

int i = (int)Convert.ChangeType("123", typeof(int));
DateTime dt = (DateTime)Convert.ChangeType("2009/12/12", typeof(DateTime));

"일반 반환 유형"요구 사항을 충족하기 위해 자체 확장 메서드를 작성할 수 있습니다.

public static T ChangeType<T>(this object obj)
{
    return (T)Convert.ChangeType(obj, typeof(T));
}

이렇게하면 다음을 수행 할 수 있습니다.

int i = "123".ChangeType<int>();

이 스레드에 답하기에는 너무 늦은 것 같습니다. 하지만 여기에 내 구현이 있습니다.

기본적으로 Object 클래스에 대한 Extention 메서드를 만들었습니다. 모든 유형, 즉 nullable, 클래스 및 구조체를 처리합니다.

 public static T ConvertTo<T>(this object value)
           {
               T returnValue;

               if (value is T variable)
                   returnValue = variable;
               else
                   try
                   {
                       //Handling Nullable types i.e, int?, double?, bool? .. etc
                       if (Nullable.GetUnderlyingType(typeof(T)) != null)
                       {
                           TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
                           returnValue = (T) conv.ConvertFrom(value);
                       }
                       else
                       {
                           returnValue = (T) Convert.ChangeType(value, typeof(T));
                       }
                   }
                   catch (Exception)
                   {
                       returnValue = default(T);
                   }

               return returnValue;
           }

System.Convert.ChangeType어떤 유형으로도 변환되지 않습니다. 다음을 생각해보십시오.

  • nullable 유형
  • 열거 형
  • 가이드 등

이러한 변환은 이 ChangeType 구현으로 가능합니다 .


Pranay의 대답의 더 깨끗한 버전

public static T ConvertTo<T>(this object value)
{
    if (value is T variable) return variable;

    try
    {
        //Handling Nullable types i.e, int?, double?, bool? .. etc
        if (Nullable.GetUnderlyingType(typeof(T)) != null)
        {
            return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value);
        }

        return (T)Convert.ChangeType(value, typeof(T));
    }
    catch (Exception)
    {
        return default(T);
    }
}

.NET에는 한 유형의 개체를 다른 유형으로 변환하는 몇 가지 규칙이 있습니다.

그러나 이러한 방법은 일반적인 방법보다 훨씬 느리므로 T.Parse(string)단일 값을 변환 할 때마다 많은 할당이 필요합니다.

For ValueString, I chose to find a suitable, static parsing method of the type using reflection, build a lambda expression calling it and cache the compiled delegate for future use (See this answer for an example).

It also fallbacks to the ways I mentioned above if the type doesn't have a suitable parsing method (See the performance section in the readme).

var v = new ValueString("15"); // struct
var i = v.As<int>(); // Calls int.Parse.

참고URL : https://stackoverflow.com/questions/3502493/is-there-any-generic-parse-function-that-will-convert-a-string-to-any-type-usi

반응형