2017-11-08 10 views
0

일부 날짜 속성이있는 복잡한 개체를 완전 복사하려고합니다. "값 ''을 (를) 올바른 날짜로 변환 할 수 없습니다. '오류가 발생합니다. 복사를 위해 아래 코드를 사용하고 있습니다. -C# 리플렉션 딥 복사본 집합 날짜 시간 값

private static object CloneProcedure(Object obj) 
{ 
    if (type.IsPrimitive || type.IsEnum || type == typeof(string)) 
    { 
     return obj; 
    } 
    else if (type.IsClass || type.IsValueType) 
    { 
     object copiedObject = Activator.CreateInstance(obj.GetType()); 
     // Get all PropertyInfo. 
     PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); 
     foreach (PropertyInfo property in properties) 
     { 
      object propertyValue = property.GetValue(obj); 
      if (propertyValue != null && property.CanWrite && property.GetSetMethod() != null) 
      { 
       property.SetValue(copiedObject, CloneProcedure(propertyValue)); 
      } 
     } 
    } 
} 

내가 누락 된 항목이 있습니까?

+0

그것은 도움이 될 것이다. – Compufreak

+0

@Compufreak 업데이트 됨 내 질문 –

답변

0

if가 허위이면 아무것도 returing하지 않습니다.

이 코드는 닷넷 4.5.2 콘솔 응용 프로그램에서 일하고 : 당신이 CloneProcedure-방법을 제공하는 경우

public class Program 
{ 
    public static void Main() 
    { 
     ComplexClass t = new ComplexClass() 
     { 
      x = DateTime.Now 
     }; 
     object t2 = CloneProcedure(t); 
     Console.WriteLine(t.x); 
     Console.ReadLine(); 
    } 
    private static object CloneProcedure(Object obj) 
    { 
     var type = obj.GetType(); 
     if (type.IsPrimitive || type.IsEnum || type == typeof(string)) 
     { 
      return obj; 
     } 
     else if (type.IsClass || type.IsValueType) 
     { 
      object copiedObject = Activator.CreateInstance(obj.GetType()); 
      // Get all PropertyInfo. 
      PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); 
      foreach (PropertyInfo property in properties) 
      { 
       object propertyValue = property.GetValue(obj); 
       if (propertyValue != null && property.CanWrite && property.GetSetMethod() != null) 
       { 
        property.SetValue(copiedObject, CloneProcedure(propertyValue)); 
       } 
      } 
     } 
     return obj; 
    } 

    public class ComplexClass 
    { 
     public DateTime x { get; set; } 
    } 
}