C# 将类强制转换为另一个类或将类转换为另一个类
我的问题显示在此代码中 我有这样的课C# 将类强制转换为另一个类或将类转换为另一个类,c#,casting,class,type-conversion,C#,Casting,Class,Type Conversion,我的问题显示在此代码中 我有这样的课 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
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;
}
您可以将类结构更改为:
public class maincs : sub1
{
public int d;
}
public class sub1
{
public int a;
public int b;
public int c;
}
然后,您可以保留sub1的列表,并将其中一些转换为mainc。您已经定义了转换,如果您希望能够转换,只需再进一步。例如:
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;
}
可以为强制转换运算符提供显式重载:
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作为接口而不是类。他想说的是: “如果您有两个类共享大多数相同的属性,则可以将对象从类
a
强制转换为类b
,并通过共享属性名称自动使系统理解分配?”
选项1:使用反射
缺点:它会比你想象的更慢
选项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; }
}
下面是对象类型的扩展:
public static T Cast<T>(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<MemberInfo> 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;
}
publicstatict-Cast(此对象myobj)
{
类型objectType=myobj.GetType();
类型目标=类型(T);
var x=Activator.CreateInstance(目标,false);
var z=来自objectType.GetMembers().ToList()中的源
其中source.MemberType==MemberTypes.Property选择source;
var d=来自target.GetMembers().ToList()中的源
其中source.MemberType==MemberTypes.Property选择source;
List members=d.Where(memberInfo=>d.Select(c=>c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
PropertyInfo PropertyInfo;
目标价值;
foreach(成员中的var memberInfo)
{
propertyInfo=typeof(T).GetProperty(memberInfo.Name);
value=myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj,null);
propertyInfo.SetValue(x,value,null);
}
返回(T)x;
}
现在您可以这样使用它:
static void Main(string[] args)
{
var cus = new customer();
cus.firstname = "John";
cus.age = 3;
employee emp = cus.Cast<employee>();
}
static void Main(字符串[]args)
{
var cus=新客户();
cus.firstname=“约翰”;
年龄=3岁;
员工emp=cus.Cast();
}
方法强制转换检查两个对象之间的公共属性并自动进行赋值。通过使用以下代码,您可以将任何类对象复制到另一个具有相同名称和相同属性类型的类对象。
public class CopyClass
{
/// <summary>
/// Copy an object to destination object, only matching fields will be copied
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sourceObject">An object with matching fields of the destination object</param>
/// <param name="destObject">Destination object, must already be created</param>
public static void CopyObject<T>(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);
}
}
}
它将objA
复制到objB
使用JSON序列化和反序列化:
这里有一些很好的答案,我只是想在这里添加一点类型检查,因为我们不能假设如果存在同名的属性,那么它们属于相同的类型。这是我的产品,它延续了上一个非常好的答案,因为我有一些小问题 在这个版本中,我允许使用者指定要排除的字段,并且在默认情况下排除任何数据库/模型特定的相关属性
public static T Transform<T>(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<objectViewModel>(serializeString);
publicstatict转换(此对象myobj,字符串excludeFields=null)
{
//组成一个不需要的成员列表
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);
//按名称查找常用成员
var sourceMembers=来自objectType.GetMembers().ToList()中的源
其中source.MemberType==MemberTypes.Property
选择来源;
var targetMembers=来自targetType.GetMembers().ToList()中的源
其中source.MemberType==MemberTypes.Property
选择来源;
var commonMembers=targetMembers.Where(memberInfo=>sourceMembers.Select(c=>c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
//删除不需要的成员
commonMembers.RemoveWhere(x=>x.Name.InList(excludeFields));
foreach(commonMembers中的var memberInfo)
{
如果(!((PropertyInfo)memberInfo).CanWrite)继续;
var targetProperty=typeof(T).GetProperty(memberInfo.Name);
如果(targetProperty==null)继续;
var sourceProperty=myobj.GetType().GetProperty(memberInfo.Name);
如果(sourceProperty==null)继续;
//检查源和目标类型是否相同
如果(sourceProperty.PropertyType.Name!=targetProperty.PropertyType.Name)继续;
var value=myobj.GetType().GetProperty(memberInfo.Name)?.GetValue(myobj,null);
如果(值==null)继续;
//设置值
SetValue(targetInstance,value,null);
}
返回(T)目标位置;
}
使用此代码,您可以将任何类对象复制到另一个具有相同名称和相同属性类型的类对象
public static T Transform<T>(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<objectViewModel>(serializeString);
JavaScriptSerializer JsonConvert=newJavaScriptSerializer();
string serializeString=JsonConvert.Serialize(objectEntity);
objectViewModel objVM=JsonConvert.Deserialize(序列化字符串);
var obj=\u account.Retrieve(电子邮件、散列);
AccountInfoResponse AccountInfoResponse=新AccountInfoResponse();
如果(obj!=null)
{
会计信息
public static T Transform<T>(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<objectViewModel>(serializeString);
var obj = _account.Retrieve(Email, hash);
AccountInfoResponse accountInfoResponse = new AccountInfoResponse();
if (obj != null)
{
accountInfoResponse =
JsonConvert.
DeserializeObject<AccountInfoResponse>
(JsonConvert.SerializeObject(obj));
}
public static T Casting<T>(this Object source)
{
Type sourceType = source.GetType();
Type targetType = typeof(T);
var target = Activator.CreateInstance(targetType, false);
var sourceMembers = sourceType.GetMembers()
.Where(x => x.MemberType == MemberTypes.Property)
.ToList();
var targetMembers = targetType.GetMembers()
.Where(x => x.MemberType == MemberTypes.Property)
.ToList();
var members = targetMembers
.Where(x => sourceMembers
.Select(y => y.Name)
.Contains(x.Name));
PropertyInfo propertyInfo;
object value;
foreach (var memberInfo in members)
{
propertyInfo = typeof(T).GetProperty(memberInfo.Name);
value = source.GetType().GetProperty(memberInfo.Name).GetValue(source, null);
propertyInfo.SetValue(target, value, null);
}
return (T)target;
}