IEquatable C# Example
IEquatable<T> Interface defines Equals method for determining equality of instances.
Example
public class Car : IEquatable<Car>
{public int Power { get; set; }
public bool Equals(Car other)
{
if (other == null) return false;
if(this.Power == other.Power) return true;
return false;
}
public override bool Equals(Object obj)
{
if (obj == null) return false;
Car carObj = obj as Car;
if (carObj == null) return false;
else return Equals(carObj);
}
}
Car c1 = new Car();
c1.Power = 100;
Car c2 = new Car();
c2.Power = 100;
if (c1.Equals(c2)) System.Windows.MessageBox.Show("Same power");
c1.Power = 100;
Car c2 = new Car();
c2.Power = 100;
if (c1.Equals(c2)) System.Windows.MessageBox.Show("Same power");
ICloneable system interface
The ICloneable interface enables you to provide a customized implementation that creates a copy of an existing object.
Definition:
public interface ICloneable
{
// Summary:
// Creates a new object that is a copy of the current instance.
//
// Returns:
// A new object that is a copy of this instance.
object Clone();
}
Example:
public class Customer : ICloneable{
public string Name { get; set; }
public Address CustomerAddress { get; set; }
public object Clone()
{
Customer newCustomer = (Customer)this.MemberwiseClone();
newCustomer.CustomerAddress = (Address)this.CustomerAddress.Clone();
return newCustomer;
}
}
public class Address : ICloneable
{
public string StreetName { get; set; }
public int StreetNumber { get; set; }
public object Clone()
{
return this.MemberwiseClone();
}
}
Customer c1 = new Customer();
c1.Name = "c1";
Address a1 = new Address();
a1.StreetName = "Street1";
a1.StreetNumber = 1;
c1.CustomerAddress = a1;
Customer custClone = (Customer)c1.Clone();
custClone.Name = "c2";
Niciun comentariu:
Trimiteți un comentariu