cast class into another class or convert class to another

前端 未结 9 649
逝去的感伤
逝去的感伤 2020-11-28 22:29

my question is shown in this code

I have class like that

public class  maincs
{
  public int a;
  public int b;
  public int c;
  public int d; 
}
         


        
9条回答
  •  被撕碎了的回忆
    2020-11-28 23:19

    There are some great answers here, I just wanted to add a little bit of type checking here as we cannot assume that if properties exist with the same name, that they are of the same type. Here is my offering, which extends on the previous, very excellent answer as I had a few little glitches with it.

    In this version I have allowed for the consumer to specify fields to be excluded, and also by default to exclude any database / model specific related properties.

        public static T Transform(this object myobj, string excludeFields = null)
        {
            // Compose a list of unwanted members
            if (string.IsNullOrWhiteSpace(excludeFields))
                excludeFields = string.Empty;
            excludeFields = !string.IsNullOrEmpty(excludeFields) ? excludeFields + "," : excludeFields;
            excludeFields += $"{nameof(DBTable.ID)},{nameof(DBTable.InstanceID)},{nameof(AuditableBase.CreatedBy)},{nameof(AuditableBase.CreatedByID)},{nameof(AuditableBase.CreatedOn)}";
    
            var objectType = myobj.GetType();
            var targetType = typeof(T);
            var targetInstance = Activator.CreateInstance(targetType, false);
    
            // Find common members by name
            var sourceMembers = from source in objectType.GetMembers().ToList()
                                      where source.MemberType == MemberTypes.Property
                                      select source;
            var targetMembers = from source in targetType.GetMembers().ToList()
                                      where source.MemberType == MemberTypes.Property
                                      select source;
            var commonMembers = targetMembers.Where(memberInfo => sourceMembers.Select(c => c.Name)
                .ToList().Contains(memberInfo.Name)).ToList();
    
            // Remove unwanted members
            commonMembers.RemoveWhere(x => x.Name.InList(excludeFields));
    
            foreach (var memberInfo in commonMembers)
            {
                if (!((PropertyInfo)memberInfo).CanWrite) continue;
    
                var targetProperty = typeof(T).GetProperty(memberInfo.Name);
                if (targetProperty == null) continue;
    
                var sourceProperty = myobj.GetType().GetProperty(memberInfo.Name);
                if (sourceProperty == null) continue;
    
                // Check source and target types are the same
                if (sourceProperty.PropertyType.Name != targetProperty.PropertyType.Name) continue;
    
                var value = myobj.GetType().GetProperty(memberInfo.Name)?.GetValue(myobj, null);
                if (value == null) continue;
    
                // Set the value
                targetProperty.SetValue(targetInstance, value, null);
            }
            return (T)targetInstance;
        }
    

提交回复
热议问题