달력

32024  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

입력폼이 조금 많은데, 자바처럼 프라퍼티 카피 하는걸 몰라서리..

msdn, 닷넷책, 웹페이지 뒤져보니 System.Reflection 이라는 네임 스페이스가 있었고,

자바에 객체 내부 프라퍼티 복사하듯이 할 수 있었당..

메소드 호출도 잘 되고.. 필드값도 잘 대입됨..

 

사용은 걍 aspx 에서  대입될 객체 생성하고 메서드에 전달해 주면 된다.

 

MyCustomProperty dest = new MyCusotmProperty();

CopyProperty(Reqeust.Form, dest);

와 같이 사용하면 됨..

string , int double, boolean 만 대입 가능함.

 

 

public static void CopyProperty(NameValueCollection src, object dest)
  {
   if(src == null) throw new Exception("src is null..");
   if(dest == null) throw new Exception("dest obj is null..");

   Type t = dest.GetType();
   
   FieldInfo[] f = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

   string key = "";
   for(int i = 0; i < src.Count; i++)
   {
    key = src.GetKey(i);

    for(int j = 0; j < f.Length; j++)
    {
     if(key.Equals(f[j].Name))
     {
      if("System.Int32".Equals(f[j].FieldType.ToString()))
      {
       f[j].SetValue(dest, Int32.Parse(src.Get(key)));
      }
      else if("System.Single".Equals(f[j].FieldType.ToString()))
      {
       f[j].SetValue(dest, Single.Parse(src.Get(key)));
      }
      else if("System.Double".Equals(f[j].FieldType.ToString()))
      {
       f[j].SetValue(dest, Double.Parse(src.Get(key)));
      }
      else if("System.Boolean".Equals(f[j].FieldType.ToString()))
      {
       f[j].SetValue(dest, Boolean.Parse(src.Get(key)));
      }
      else if("System.Decimal".Equals(f[j].FieldType.ToString()))
      {
       f[j].SetValue(dest, Decimal.Parse(src.Get(key)));
      }
      else if("System.String".Equals(f[j].FieldType.ToString()))
      {
       f[j].SetValue(dest, src.Get(key));
      }
      else if("System.Object".Equals(f[j].FieldType.ToString()))
      {
       f[j].SetValue(dest, src.Get(key));
      }       
     }     
    }    
   }
  } // end CopyProperty..

Posted by tornado
|