سؤال

How can I set all of the properties of an object to be equal to another? Like in my example, TCar is basically a Car, how can I set the shared variables to be equal? In Java if I remember correctly, I can do this easily.

class Car {

}

class TCar : Car {

}

Car car = new Car();
TCar datcar = new TCar();
datcar = car; Error? Isn't the datcar is a 'Car' too?

I don't want to manually set everything.

هل كانت مفيدة؟

المحلول

Your code won't work because a Car isn't a TCar. The other way around would work: car = datcar.

However that will probably not do what you expect as it will only make the two references car and datcar point to the same TCar object.

If you want to keep the objects as separate ones but update all the properties of one object with the values of those of the properties of the other one you will have to assign them one by one. Or you can use AutoMapper which does exactly that automatically.

نصائح أخرى

datacar is a Car, but it's specifically a TCar so the reference to car can't be set to it because they aren't of the same type in memory. Further, what you're doing won't set the property values, it will just set the reference (or pointer) in memory.

What you're looking for is a Clone to another type. Consider adding an extension method for cloning that object like this:

namespace System
{
    public static class Extensions
    {
        public static TOut Clone<TOut>(this Car input) where TOut : Car
        {
            var o = Activator.CreateInstance(typeof(TOut));
            foreach (var prop in typeof(Car).GetProperties())
            {
                prop.SetValue(o, prop.GetValue(input));
            }
        }
    }
}

and so now you can do this:

TCar datacar = car.Clone<TCar>();

You can create a new object with the properties of the other one:

Car car = new Car("jeep");

TCar datCar = new Tcar {
 Brand = car.Brand
};

Or you can create explicit/implicit operators or use a mapping tool like AutoMapper.

In C# you'll need conversion operators - and, in the case you mentioned, it would be an Implicit conversion.

Quoting from MSDN: "C# enables programmers to declare conversions on classes or structs so that classes or structs can be converted to and/or from other classes or structs, or basic types. Conversions are defined like operators and are named for the type to which they convert. Either the type of the argument to be converted, or the type of the result of the conversion, but not both, must be the containing type."

It would look something like this:

class Car
{
    // ...other members 

    // User-defined conversion from TCar to Car
    public static implicit operator Car(TCar d)
    {
        return new Car(d);
    }
    //  User-defined conversion from Car to TCar
    public static implicit operator TCar(Car d)
    {
        return new TCar(d);
    }
}

Source: http://msdn.microsoft.com/en-us/library/09479473(v=vs.90).aspx

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top