2013-08-01 36 views
0

//這裏我如何設置targetPi?我認爲定義是不正確的,但我不知道如何解決這個問題?

object target = Activator.CreateInstance(typeof(T)); 

    PropertyInfo[] sourceProperties = sourceType.GetProperties(); 

    foreach (PropertyInfo pi in sourceProperties) 
    { 
     PropertyInfo targetPi = typeof(T).GetProperty(pi.Name); //returns null why? 

     object piValue = pi.GetValue(source, null); 

     try 
     { 
       if (targetPi != null) // it doesnt work 
       { 
        targetPi.SetValue(target,piValue, null); // target has typeof(T) 
       } 
     } 
     catch { }   
    } 
    return(T)target; 
} 
+1

你還沒有告訴我們任何東西* *關於你想要達到的目標。你剛剛發佈格式不正確的代碼,就這些。請參閱http://tinyurl.com/so-hints –

回答

0

一些代碼這個工作對我來說:

struct Item1 { public double Foo { get; set; } } 
struct Item2 { public double Foo { get; set; } } 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Item1 i1 = new Item1(); 
     CopyDynamically(new Item2 { Foo = 42 }, ref i1); 

     Console.WriteLine(i1.Foo); 


     i1 = CopyDynamically<Item1>(new Item2 { Foo = 3.14 }); 

     Console.WriteLine(i1.Foo); 
    } 

    static void CopyDynamically<T>(object source, ref T target) 
    { 
     if (source == null) 
      throw new ArgumentNullException("source"); 
     if (target == null) 
      throw new ArgumentNullException("target"); 

     foreach (PropertyInfo pi in source.GetType().GetProperties()) 
     { 
      PropertyInfo targetPi = typeof(T).GetProperty(pi.Name); 

      if (targetPi != null && targetPi.SetMethod != null && targetPi.SetMethod.IsPublic) 
      { 
       object val = pi.GetValue(source, null); 
       object o = target; 

       try { targetPi.SetValue(o, val, null); } 
       catch { } 

       target = (T)o; 
      } 
     } 
    } 
    static T CopyDynamically<T>(object source, params object[] ctorArgs) 
    { 
     T target = (T)Activator.CreateInstance(typeof(T), ctorArgs); 

     CopyDynamically(source, ref target); 

     return target; 
    } 
} 
+0

其實,我一直在試圖映射到桌到桌和我弄明白,這個錯誤是我的代碼的背景。(表變量名是錯誤的).Thanks爲你的幫助mtman.Also任何人都可以問我是否有問題:) – sssD

相關問題