public 
   interface 
   IName  
   
  
       
   { 
   
  
           
   int 
   Age { 
   get
   ; 
   set
   ; } 
   
  
           
   string 
   Name { 
   get
   ; 
   set
   ; } 
   
  
       
   } 
   
  
     
   
  
       
   public 
   class 
   Person  
   
  
       
   { 
   
  
           
   public 
   int 
   Age{
   get
   ;
   set
   ;} 
   
  
           
   public 
   string 
   Name { 
   get
   ; 
   set
   ; } 
   
  
           
   public 
   Person() 
   
  
           
   { } 
   
  
           
   public 
   Person(
   string 
   name,
   int 
   age) 
   
  
           
   { 
   
  
               
   Name = name; 
   
  
               
   Age = age; 
   
  
           
   } 
   
  
       
   } 
   
  
     
   
  
       
   public 
   class 
   EmptyEntity : IName 
   
  
       
   { 
   
  
           
   public 
   string 
   Name { 
   get
   ; 
   set
   ; } 
   
  
           
   public 
   int 
   Age { 
   get
   ; 
   set
   ; } 
   
  
       
   } 
   
  
     
   
  
       
   public 
   class 
   ClassToInterface 
   
  
       
   { 
   
  
           
   /// <summary> 
   
  
           
   ///  
   
  
           
   /// </summary> 
   
  
           
   /// <typeparam name="T"></typeparam> 
   
  
           
   /// <typeparam name="TResult">it implements the interface.</typeparam> 
   
  
           
   /// <returns></returns> 
   
  
           public static IName ConvertClassToInterface<T>(T obj) 
   
  
           { 
   
  
               IName entity=new EmptyEntity(); 
   
  
               PropertyInfo[] descProperties = typeof(IName).GetProperties(); 
   
  
               Type type = obj.GetType(); 
   
  
               foreach(PropertyInfo propertyInfo in descProperties) 
   
  
               { 
   
  
                   propertyInfo.SetValue(entity,type.GetProperty(propertyInfo.Name).GetValue(obj, null), null); 
   
  
               } 
   
  
               Console.WriteLine("Result:{0}={1}",entity.Name,entity.Age); 
   
  
               return entity; 
   
  
           } 
   
  
     
   
  
       
   }
   
 
 
转载于:https://www.cnblogs.com/hongjiumu/archive/2012/11/17/2774729.html