-2

注意:所有代码都是手写的,所以语法可能是错误的我不知道

我想合并由 XSD2Code 工具生成的部分类的两个对象,但无法找出如何。

我发现这篇文章对如何在 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
4

2 回答 2

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(), ... });

看起来我没有直接回答你的问题,但根据我的经验,你最好尽可能保持简单。这样,您可以在两周后回顾您的代码,并且仍然了解发生了什么。

祝你好运!

于 2013-08-29T13:15:05.310 回答
-1

Your question has nothing to do with partial classes. A partial class is one whose code is split between multiple files.

There's nothing "built-in" to do what you want. You could use reflection to loop through all of the properties and add any numeric values together, but you would still have to account for different numeric types (there's not a generic way to add two numeric values whose types are not known at compile-time).

于 2013-08-29T12:54:26.773 回答