注意:所有代码都是手写的,所以语法可能有误我不知道
我想合并由XSD2Code工具生成的部分类的两个对象,但无法找到方法。
我发现这篇帖子对How to combine a Partial Class Object in C#?无效,因为我所拥有的Partial类有数百个属性和属性。此代码也是复制而不是合并left.price = right.price;
示例
Public Method_1()
{
FruitCrate fcA = new FruitCrate();
fcA = Method_2() + Method_3();
}
Public FruitCrate Method_2()
{
FruitCrate fcB = new FruitCrate();
fcB.Name = ..
fcB..... hundred of properties..
return fcB;
}
Public FruitCrate Method_3()
{
FruitCrate fcC = new FruitCrate();
fcC.Name = ..
fcC..... hundred of properties..
return fcC;
}
这是部分类的样子,
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.1433")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class FruitCrate{
private List<FruitCrate> FruitCrate;
private static System.Xml.Serialization.XmlSerializer serializer;
public FruitCrate() {
this.FruitCrateField = new List<FruitCrateField>();
}
[System.Xml.Serialization.XmlArrayAttribute(Order=0)]
[System.Xml.Serialization.XmlArrayItemAttribute("FruitCrate", IsNullable=false)]
public List<FruitCrate> FruitCrate{
get {
return this.FruitCrate;
}
set {
this.FruitCrateField = value;
}
}
//soo on it's a large auto generated class
答案 0 :(得分:0)
为什么不实现一个功能来为您添加?对于上面提到的仅有两个蛋糕的情况,它可能看起来像:
public static FruitCake MergeCakes(FruitCake A, FruitCake B)
{
FruitCake mergedCake = new FruitCake();
// Do your merging, like for instance
mergedCake.Price = A.Price + B.Price;
return mergedCake;
}
然后你可以像这样添加:
FruitCrate fcA = new FruitCake();
fcA = MergeCakes(Method_2(), Method_3());
如果您需要合并大量蛋糕,可以使用List输入实现MergeCakes函数,例如:
public static FruitCake MergeCakes(List<FruitCake> cakes)
{
if(cakes != null)
{
FruitCake mergedCake = new FruitCake();
// Do your merging, like for instance
foreach(var cake in cakes)
{
mergedCake.Price += cake.Price;
}
}
return mergedCake;
}
然后按如下方式添加:
FruitCrate fcA = new FruitCake();
fcA = MergeCakes(new List<FruitCake>(){ Method_2(), Method_3()), Method_4(), Method_5(), ... });
看起来我似乎并没有直接回答你的问题,但根据我的经验,你最好尽可能保持尽可能简单的事情。这样你可以在两周后回顾你的代码并仍然了解最新情况。
祝你好运!答案 1 :(得分:-1)
您的问题与部分课程无关。部分类是代码在多个文件之间分割的类。
没有什么“内置”可以做你想要的。你可以使用反射循环遍历所有属性并将任何数值加在一起,但你仍然需要考虑不同的数字类型(没有通用的方法来添加两个数值类型的类型是在编译时不知道。