将类转换为另一个类或将类转换为另一个类

我的问题显示在此代码中

我有这样的课

public class maincs { public int a; public int b; public int c; public int d; } public class sub1 { public int a; public int b; public int c; } public void methoda (sub1 model) { maincs mdata = new maincs(){a = model.a , b = model.b , c= model.c} ; // is there is a way to directly cast class sub1 into main like that mdata = (maincs) model; } 

他想说的是:

“如果你有两个共享大多数相同属性的类,你可以将一个对象从类a为类b并自动使系统通过共享属性名来理解赋值?”

选项1:使用reflection

缺点:它会比你想象的更慢。

选项2:使一个类派生自另一个,第一个具有共同属性,另一个具有共同属性的扩展。

缺点:加上! 如果您在应用程序中为两层执行此操作,则两个层将耦合!

让我们:

 class customer { public string firstname { get; set; } public string lastname { get; set; } public int age { get; set; } } class employee { public string firstname { get; set; } public int age { get; set; } } 

现在这里是Object类型的扩展:

 public static T Cast(this Object myobj) { Type objectType = myobj.GetType(); Type target = typeof(T); var x = Activator.CreateInstance(target, false); var z = from source in objectType.GetMembers().ToList() where source.MemberType == MemberTypes.Property select source ; var d = from source in target.GetMembers().ToList() where source.MemberType == MemberTypes.Property select source; List members = d.Where(memberInfo => d.Select(c => c.Name) .ToList().Contains(memberInfo.Name)).ToList(); PropertyInfo propertyInfo; object value; foreach (var memberInfo in members) { propertyInfo = typeof(T).GetProperty(memberInfo.Name); value = myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj,null); propertyInfo.SetValue(x,value,null); } return (T)x; } 

现在你像这样使用它:

 static void Main(string[] args) { var cus = new customer(); cus.firstname = "John"; cus.age = 3; employee emp = cus.Cast(); } 

方法转换检查两个对象之间的公共属性并自动执行赋值。

您已经定义了转换,如果您希望能够进行转换,您只需要更进一步。 例如:

 public class sub1 { public int a; public int b; public int c; public static explicit operator maincs(sub1 obj) { maincs output = new maincs() { a = obj.a, b = obj.b, c = obj.c }; return output; } } 

然后,它允许你做类似的事情

 static void Main() { sub1 mySub = new sub1(); maincs myMain = (maincs)mySub; } 

使用JSON序列化和反序列化:

 using Newtonsoft.Json; Class1 obj1 = new Class1(); Class2 obj2 = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(obj1)); 

要么:

 public class Class1 { public static explicit operator Class2(Class1 obj) { return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(obj)); } } 

然后,它允许你做类似的事情

 static void Main() { Class1 obj1 = new Class1(); Class2 obj2 = (Class2)obj1; } 

您可以将类结构更改为:

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

然后你可以保留一个sub1列表并将其中一些转换为mainc。

您可以为强制转换运算符提供显式重载:

 public static explicit operator maincs(sub1 val) { var ret = new maincs() { a = val.a, b = val.b, c = val.c }; return ret; } 

另一种选择是使用具有a,b和c属性的接口,并在两个类上实现接口。 然后将methoda的参数类型作为接口而不是类。

通过使用以下代码,您可以将任何类对象复制到另一个类对象,以获得相同名称和相同类型的属性。

 public class CopyClass { ///  /// Copy an object to destination object, only matching fields will be copied ///  ///  /// An object with matching fields of the destination object /// Destination object, must already be created public static void CopyObject(object sourceObject, ref T destObject) { // If either the source, or destination is null, return if (sourceObject == null || destObject == null) return; // Get the type of each object Type sourceType = sourceObject.GetType(); Type targetType = destObject.GetType(); // Loop through the source properties foreach (PropertyInfo p in sourceType.GetProperties()) { // Get the matching property in the destination object PropertyInfo targetObj = targetType.GetProperty(p.Name); // If there is none, skip if (targetObj == null) continue; // Set the value in the destination targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null); } } } 

呼叫方法就像,

 ClassA objA = new ClassA(); ClassB objB = new ClassB(); CopyClass.CopyObject(objOfferMast, ref objB); 

它会将objA复制到objB

这里有一些很好的答案,我只是想在这里添加一些类型检查,因为我们不能假设如果属性存在同名,那么它们属于同一类型。 这是我的产品,它延续了之前非常优秀的答案,因为我有一些小问题。

在此版本中,我允许使用者指定要排除的字段,并且默认情况下也排除任何数据库/模型特定的相关属性。

  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; } 

使用此代码,您可以将任何类对象复制到另一个类对象,以获得相同名称和相同类型的属性。

 JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); string serializeString = JsonConvert.Serialize(objectEntity); objectViewModel objVM = JsonConvert.Deserialize(serializeString);