2017-11-08 5 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がfalseの場合、あなたは何も修復していません。

このコードは、.NET 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; } 
    } 
}