Update from comment:
I need to extend linq-to-sql classes by own parameters and dont want to touch any generated classes. Any better suggestes are welcome. But I also don't want to do all attributes assignments all time again if the linq-to-sql classes are changing. so if vstudio generates new attribute to a class i have my own extended attributes kept separate, and the new innerited from the class itself
Original question:
i'm not sure if it's possible. I have a class car and a class mycar extended from class car. Class mycar has also a string list. Only difference.
How can i cast now any car object to a mycar object without assigning all attributes each by hand. Like:
Car car = new Car();
MyCar mcar = (MyCar) car;
or
MyCar mcar = new MyCar(car);
or however i can extend car w开发者_运维知识库ith own variables and don't have to do always
Car car = new Car();
MyCar mcar = new MyCar();
mcar.name = car.name;
mcar.xyz = car.xyz;
...
Thanks.
In response to your comment on the question, the Linq-To-Sql classes are generated as partial. This means you can have separate code files with the same class names declared as partial to add the extra properties you want.
E.g. Your Ling-To-Sql designer class will be:
public partial class Car
{
.... lots of auto generated stuff ....
}
You can have your own separate file (in the same project) called Car.cs:
public partial class Car
{
public MyCustomStuff{ get; set; }
}
And the two classes will be merged together. Just make sure they are in the same namespace.
You can create a copy constructor accepting a base class parameter in the derived class:
class MyCar {
public MyCar(Car car) {
name = car.name;
// etc
}
}
you can't definately cast a Car
as MyCar
because there is no guarantee that the Car
is a MyCar
. You can try the cast and see if it works, or you can use the as
keyword to try the cast and get null if it fails.
How are the properties set in Car
? Why can't MyCar
just use the same technique for setting its properties? After all it is a Car
. Why do you want to create a MyCar
from a Car
? Why not just create a MyCar
in the first place?
You could also create a constructor in MyCar
which takes a Car
and assign the properties of MyCar
to those of Car
in the constructor.
You might also consider using the decorator pattern as an alternative to subclassing, and have your MyCar
delegate the calls to the wrapped Car
There are several options you can use:
implicit or explicit operator
public static explicit operator Car(MyCar source)
a copy constructor
public MyCar(Car source)
an extension method
public static class CarExtensions {
public static MyCar Create(this Car source) }
精彩评论