问题描述
我的问题显示在这段代码中
My question is shown in this code
我有这样的课
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 a way to directly cast class Sub1 into MainCS like that
mdata = (MainCS) model;
}
推荐答案
他想说的是:
如果你有两个类共享大部分相同的属性,你可以将一个对象从类 a
转换为类 b
并自动让系统通过以下方式理解分配共享属性名称?"
"If you have two classes which share most of the same properties you can cast an object from class a
to class b
and automatically make the system understand the assignment via the shared property names?"
选项1:使用反射
缺点:它会比你想象的更慢.
Disadvantage : It's gonna slow you down more than you think.
选项 2:让一个类从另一个类派生,第一个类具有公共属性,其他类是该类的扩展.
Option 2: Make one class derive from another, the first one with common properties and other an extension of that.
缺点:耦合!如果您在应用程序中为两层执行此操作,那么这两层将被耦合!
Disadvantage: Coupled! if your're doing that for two layers in your application then the two layers will be coupled!
假设:
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; }
}
现在这里是对象类型的扩展:
Now here is an extension for Object type:
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;
}
现在你可以这样使用它:
Now you use it like this:
static void Main(string[] args)
{
var cus = new customer();
cus.firstname = "John";
cus.age = 3;
employee emp = cus.Cast<employee>();
}
方法转换检查两个对象之间的公共属性并自动进行分配.
Method cast checks common properties between two objects and does the assignment automatically.
这篇关于将类转换为另一个类或将类转换为另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!