When designing the parent object, you will encounter the situation where the parameter of the object method is the class itself, and then the sub-object will implement this method, for example, compare whether the object is equal. In this scenario, it is usually designed to write the following example, first performing transformation and comparison in the sub-object.
This is a design that can work normally, but the sub-object method parameter will be the parent object type, rather than the sub-object type.
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { ChildAddress addressA = new ChildAddress(); addressA.Value001 = "123"; ChildAddress addressB = new ChildAddress(); addressB.Value001 = "123"; Console.WriteLine(addressA.EqualAddress(addressB)); Console.ReadLine(); } }}namespace ConsoleApplication1{ public abstract class Address { // Methods public abstract bool EqualAddress(Address address); } public class ChildAddress : Address { // Properties public string Value001 { get; set; } // Methods public override bool EqualAddress(Address address) { // Require ChildAddress childAddress = address as ChildAddress; if (childAddress == null) return false; // Equal if (childAddress.Value001 == this.Value001) { return true; } else { return false; } } }}
In some scenarios, if you want the parameters of the sub-object method to reference the sub-object type as the input type, you can achieve this goal according to the following generic syntax.
namespace ConsoleApplication2{ class Program { static void Main(string[] args) { ChildAddress addressA = new ChildAddress(); addressA.Value001 = "123"; ChildAddress addressB = new ChildAddress(); addressB.Value001 = "123"; Console.WriteLine(addressA.EqualAddress(addressB)); Console.ReadLine(); } }}namespace ConsoleApplication2{ public abstract class Address<TAddress> where TAddress : Address<TAddress> { // Methods public abstract bool EqualAddress(TAddress address); } public class ChildAddress : Address<ChildAddress> { // Properties public string Value001 { get; set; } // Methods public override bool EqualAddress(ChildAddress address) { // Equal if (address.Value001 == this.Value001) { return true; } else { return false; } } }}
The above two examples are mainly different in application scenarios.
The first example is commonly used: the sub-object is used as the object of the injection framework.
The second example is commonly used when sub-objects are provided to external systems.