Assign object of a class and object of a class x

2

Someone knows how I can do the following: I have a class X and another class Y, both have the same attributes in the same order and others, they are practically identical only with a different name, so I want to do something like:

X objX = new X(....);
Y objY = objX;

Does anyone know if doing that can be done ???

    
asked by RSillerico 15.06.2016 в 17:37
source

3 answers

4

There is a Heritage:

// Clase A (Padre)
class A
{
    public int X;
    public int Y;
    public A(int x, int y) { this.X = x; this.Y = y; }
}

// Clase B : Hijo
class B : A
{
    public int Z; // Extendimos la clase A, en la clase B.
    public B(int x, int y) : base(x, y) { Z = 0; }
}

And by calling them we can do so:

B Child = new B(2, 3); // X = 2, Y = 3, Z = 0;
A Parent = B; // Z practicamente no existe, pero puede ser accesible con un cast.

And then, apart from the inheritance, there is also something like a copy, which I think is more suited to your case, since you have two classes with the same members ...

Imagine that we have class A:

class A
{
    public int X;
    public int Y;
    public A(...) { /* ... */ }
}

And a class B:

class B
{
    public int X;
    public int Y;
    public B(...) { /* ... */ }
    public B(A elem) 
    {
        this.X = A.X;
        this.Y = A.Y;
    }
}

If you notice, in the class A and B we have the same attributes, what makes them different is the identifier, in the class B I have put a copy constructor, which complies with what you are looking for and you do not need to inherit any class, so if you want to have the same values of a variable type A in a type B :

A MiObjeto = new A(5, 3); // X = 5, Y = 3.
B MiSegundoObjeto = new B(A); // Donde se llama al constructor copia.

If we try:

Console.WriteLine("A.X: " + A.X + ", B.X: " + B.X); // Ambos imprimen 5
Console.WriteLine("A.Y: " + A.Y + ", B.Y: " + B.Y); // Ambos imprimen 3 

The difference between the two is that the copy constructor creates a new instance with all the members accessible from its own instance, while the hidden inheritance members added or extended from your new daughter class, although it can be accessed through of a cast (following the inheritance):

B Nueva = (B)A; // Obliga a la clase a convertirse en la clase hija.
    
answered by 15.06.2016 в 19:10
2

If you implement herencia in the classes you could assign them as you mentioned

An example

public class Y 
{
    public string Prop1 {get;set;}
    public int Prop2 {get;set;}
}

public class X : Y
{
    public string Prop3 {get;set;}
}

public class Program
{
    public static void Main()
    {
        X objX = new X();
        Y objY = objX;
    }
}
    
answered by 15.06.2016 в 18:06
1

That is solved using inheritance, you create a parent class using the fields that both classes share and in the daughter classes you use the different fields, here is an example:

// WorkItem implicitly inherits from the Object class.
public class WorkItem
{
// Static field currentID stores the job ID of the last WorkItem that
// has been created.
private static int currentID;

//propiedades.
protected int ID { get; set; }
protected string Title { get; set; }
protected string Description { get; set; }
protected TimeSpan jobLength { get; set; }

// Constructor por defecto. Si una clase derivada no invoca a un constructor base de manera explicita, el constructor por defecto es llamado de forma implícita

public WorkItem()
{
    ID = 0;
    Title = "Titulo Random";
    Description = "Descripcion Random.";
    jobLength = new TimeSpan();
}

// Instance constructor that has three parameters.
public WorkItem(string title, string desc, TimeSpan joblen)
{
    this.ID = GetNextID();
    this.Title = title;
    this.Description = desc;
    this.jobLength = joblen;
}

// Static constructor to initialize the static member, currentID. This
// constructor is called one time, automatically, before any instance
// of WorkItem or ChangeRequest is created, or currentID is referenced.
static WorkItem()
{
    currentID = 0;
}


protected int GetNextID()
{
    // currentID is a static field. It is incremented each time a new
    // instance of WorkItem is created.
    return ++currentID;
}

// Method Update enables you to update the title and job length of an
// existing WorkItem object.
public void Update(string title, TimeSpan joblen)
{
    this.Title = title;
    this.jobLength = joblen;
}

// Virtual method override of the ToString method that is inherited
// from System.Object.
public override string ToString()
{
    return String.Format("{0} - {1}", this.ID, this.Title);
}
}

// ChangeRequest derives from WorkItem and adds a property (originalItemID) 
// and two constructors.
public class ChangeRequest : WorkItem
{
protected int originalItemID { get; set; }

// Constructors. Because neither constructor calls a base-class 
// constructor explicitly, the default constructor in the base class
// is called implicitly. The base class must contain a default 
// constructor.

// Default constructor for the derived class.
public ChangeRequest() { }

// Instance constructor that has four parameters.
public ChangeRequest(string title, string desc, TimeSpan jobLen,
                     int originalID)
{
    // The following properties and the GetNexID method are inherited 
    // from WorkItem.
    this.ID = GetNextID();
    this.Title = title;
    this.Description = desc;
    this.jobLength = jobLen;

    // Property originalItemId is a member of ChangeRequest, but not 
    // of WorkItem.
    this.originalItemID = originalID;
}
}

class Program
{
static void Main()
{
    // Create an instance of WorkItem by using the constructor in the 
    // base class that takes three arguments.
    WorkItem item = new WorkItem("Fix Bugs",
                                 "Fix all bugs in my code branch",
                                 new TimeSpan(3, 4, 0, 0));

    // Create an instance of ChangeRequest by using the constructor in
    // the derived class that takes four arguments.
    ChangeRequest change = new ChangeRequest("Change Base Class Design",
                                             "Add members to the class",
                                             new TimeSpan(4, 0, 0),
                                             1);

    // Use the ToString method defined in WorkItem.
    Console.WriteLine(item.ToString());

    // Use the inherited Update method to change the title of the 
    // ChangeRequest object.
    change.Update("Change the Design of the Base Class",
        new TimeSpan(4, 0, 0));

    // ChangeRequest inherits WorkItem's override of ToString.
    Console.WriteLine(change.ToString());

    // Keep the console open in debug mode.
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();
}
}
/* Output:
1 - Fix Bugs
2 - Change the Design of the Base Class
*/

Reference: link

    
answered by 15.06.2016 в 18:05