2015-01-02 7 views
4

Reflection으로 내 모델의 특정 속성을 업데이트하십시오. DateTime 유형의 속성을 제외한 다른 모든 유형의 내 모델에서 작동합니까?nullable datetime의 속성 값을 설정하십시오.

코드 : 다음 오류가 Convert.ChangeType 부분에 발생합니다

public void UpdateProperty(Guid topicGuid, string property, string value) 
{ 
    var topic = Read(topicGuid); 
    PropertyInfo propertyInfo = topic.GetType().GetProperty(property); 
    propertyInfo.SetValue(topic, Convert.ChangeType(value, propertyInfo.PropertyType), null); 

    topic.DateModified = DateTime.Now; 

    Save(); 
} 

:

Invalid cast from 'System.String' to 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' 

방법이가 해결 될 수 있는가? 업데이트

는 다니엘 A. 화이트의 솔루션과 협력있어

코드 (아마도 약간의 미세 조정이 필요하지만 그것은 작동) 업데이트 : 값을 변환하는

public void UpdateProperty(Guid topicGuid, string property, string value) 
{ 
    var topic = Read(topicGuid); 

    PropertyInfo propertyInfo = topic.GetType().GetProperty(property); 

    object changedType = propertyInfo.PropertyType == typeof(DateTime) || propertyInfo.PropertyType == typeof(DateTime?) 
      ? DateTime.Parse(value) 
      : Convert.ChangeType(value, propertyInfo.PropertyType); 

    propertyInfo.SetValue(topic, changedType, null); 

    topic.DateModified = DateTime.Now; 

    Save(); 
} 
+2

실제 오류 메시지가 무엇에 의해

Convert.ChangeType(value, propertyInfo.PropertyType) 

을 대체하려고? –

+0

'System.String'에서 'System.Nullable'1 로의 잘못된 캐스트'[System.DateTime, mscorlib, 버전 = 4.0.0.0, 문화 = 중립, PublicKeyToken = b77a5c561934e089] ' – Dairo

+8

'DateTime.Parse'를 사용해야합니다. 또는'TryParse' 또는 관련. –

답변

0

시도를 ~ DateTime : DateTime.Parse (value);

4

은 (테스트되지 않음)

Convert.ChangeType(value, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType) 

+0

이 작품처럼 보입니다 ... OP까지 !! :) –