cast the Parent object to Child object in C#

前端 未结 7 1245
春和景丽
春和景丽 2020-12-01 07:00

Hi i want to cast the Parent object to Child object in C#

public class Parent
{
    public string FirstName {get; set;}
    public string LastName {get; set;         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 07:30

    This is what I came up with form my solution.

        public static void ShallowConvert(this T parent, U child)
        {
            foreach (PropertyInfo property in parent.GetType().GetProperties())
            {
                if (property.CanWrite)
                {
                    property.SetValue(child, property.GetValue(parent, null), null);
                }
            }
        }
    

提交回复
热议问题