问题
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 with 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.
回答1:
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.
回答2:
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
}
}
回答3:
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
回答4:
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) }
来源:https://stackoverflow.com/questions/2801975/how-can-i-extend-a-linq-to-sql-class-without-having-to-make-changes-every-time-t