2013-08-01 3 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

На самом деле, я пытался сопоставить таблицу с таблицей, и я понял, ошибка была на моем фоне кодов (имя таблицы было неправильным). ваша помощь mtman.Also каждый может спросить меня, если есть вопрос :) – sssD