2016-06-13 2 views
-3

개체의 속성 유형을 변경하려고하는데이 코드를 사용하면 convert.changetype을 문자열에서 guid로 변환하지 않습니다. guid는 nullable입니다 그래서 내가 전달하지 않을 기본 메서드는 nullable 함께 작동하지 않는 설명했다 기사를 따를 수없는 유일한 것은 내가 x 값을 y 엔터티 형식으로 변환하는 해결할 수없는 x 알고 문자열 및 y guid입니다. .제네릭 형식으로 캐스팅하는 것이 Guid에서 실패합니다

사용자 정의 변경 유형 클래스 이런 식으로 변환하는 시도 Null 허용 문제

public static object ChangeType(object value, Type conversionType) 
    { 
     // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're 
     // checking properties on conversionType below. 
     if (conversionType == null) 
     { 
      throw new ArgumentNullException("conversionType"); 
     } // end if 

     // If it's not a nullable type, just pass through the parameters to Convert.ChangeType 

     if (conversionType.IsGenericType && 
      conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) 
     { 
      // It's a nullable type, so instead of calling Convert.ChangeType directly which would throw a 
      // InvalidCastException (per http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx), 
      // determine what the underlying type is 
      // If it's null, it won't convert to the underlying type, but that's fine since nulls don't really 
      // have a type--so just return null 
      // Note: We only do this check if we're converting to a nullable type, since doing it outside 
      // would diverge from Convert.ChangeType's behavior, which throws an InvalidCastException if 
      // value is null and conversionType is a value type. 
      if (value == null) 
      { 
       return null; 
      } // end if 

      // It's a nullable type, and not null, so that means it can be converted to its underlying type, 
      // so overwrite the passed-in conversion type with this underlying type 
      NullableConverter nullableConverter = new NullableConverter(conversionType); 
      conversionType = nullableConverter.UnderlyingType; 
     } // end if 

     // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a 
     // nullable type), pass the call on to Convert.ChangeType 

     return Convert.ChangeType(value, conversionType); 
    } 

를 건너 뜁니다하지만 난 T 유형을 가져올 수 없습니다

(T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text); 
(instance.GetType())TypeDescriptor.GetConverter(instance.GetType().).ConvertFromInvariantString(text); 
+0

그래서 무엇이 문제입니까? – dotnetom

+0

convert.changeType (value, type)을 사용하여 문자열을 guid로 처리 할 때 작동하지 않습니다. –

+0

정말로이 코드를 직접 작성한 경우 왜 질문에 시도하지 않았습니까? 그대로 서서, 당신의 질문은 당신이 시도했다는 증거가 없기 때문에 투표가 종료되고 닫힙니다. 그리고 당신은 질문조차하지 않았습니다. 문제를 진술하고 질문을 암시하지 마십시오. 질문을 철저히 묻습니다. –

답변

-2

당신이 경우 문자열을 GUID로 변환하려고 할 때 왜 Guid 생성자 (예 : {Guid temp = new Guid (stringValue)})로 전달하지 않습니까? 문자열이 비어 있으면 빈 GUID를 만듭니다

+0

유형이 일반이므로 새로운 Guid (문자열)가 될 수 없습니다 –

+0

그러나 문자열에서 Guid로 이동해야한다는 것이 알려진 경우 일반, 당신은 유전자를 문자열로 변환하고 Guid를 만듭니다. –

관련 문제