How to combine a Partial Class Object in C#?

放肆的年华 提交于 2019-12-01 17:57:49

How about you just overload the + operator ?

    public static Sample operator +(Sample left, Sample right)
    {
        left.price = right.price;
        return left;
    }

This has actually nothing to do with partial classes. Partial class is a single class, which is "geographically" declared more than in one file.

File1.cs:

public partial class File { public string Prop2 { get;set; } }

File2.cs:

public partial class File { public int Prop1 { get;set; } }

which will, when compiled, produce:

public partial class File 
{
     public string Prop2 { get;set; } 
     public int Prop1 { get;set; } 
}

For what you are asking.
There is no such method, which would combine two different instances into one. You should write it by your own.

UPDATE:
You may ask, why there is no such method. But how would it handle situation like:

Sample sampleA = new Sample();
sampleA.name = "test";
sampleA.price = 200;

Sample sampleB = new Sample();
sampleB.price = 100;

Sample sampleC = sampleA + sampleB; // what would be the value of price here: from sampleA or sampleB?

You could accomplish this by overloading the + operator on your class. Something like this

public static Sample operator +(Sample sampleA, Sample sampleB){
    return new Sample() { Name = sampleA.Name, Price = sampleB.Price };
}
Steven Jeuris

As Eric Yin mentioned in his answer, partial class is an inappropriate name to use as it refers to something else entirely.

It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.

First of all you should consider whether using the addition operator would be a conceptually good choice. Is it obvious/uambiguous what the resulting object will be?

At first sight, I would interpret the behavior you are looking for as combining two objects by using all their non-null values. When both objects have the same field with a non-null value, how would you handle that?

Considering this is the behavior you are after, you could overload the addition operator as in Gabe's answer. When your class/struct only contains nullable values you could let the addition copy all values from one object to the other where one contains a value and the other a null value. I'd throw an exception when both objects contain a value.

As a last point, reflect on how you ended up with having to implement this behavior. It's my guess there is an underlying design issue you could address instead. You probably shouldn't use objects which only store partial data.


As another alternative the new dynamic keyword in C# also comes to mind. It might be worthwhile to check that out as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!