问题
In C# you have object initializers to initialize fields of objects at creation time without using a constructor.
Now I'm wondering if there is an equivalent to classes which means that you can 'initialize' properties of classes when defining subclasses without actually using an override syntax but simply declaring what the value of a known property is.
Example:
public abstract class Car {
public abstract string Name { get; }
}
// usual approach
public class Mustang : Car {
public overwrite string Name { get { return "Ford Mustang"; } }
}
// my idea of avoiding boilerplate code
public class Mustang : Car { Name = "Ford Mustang" }
Is there a way to accomplish this? If there is none, could T4 templates be of any help?
回答1:
To make rekire's example clearer, you'd write something like:
public abstract class Car
{
public string Name { get; private set; }
protected Car(string name)
{
this.Name = name;
}
}
public class Mustang : Car
{
public Mustang() : base("Mustang")
{
}
}
EDIT: Another option is to use attributes, where you'd write:
[CarName("Mustang")]
public class Mustang : Car
... having written appropriate reflection code in Car
. I would strongly recommend that you don't though. Of course, attributes may be useful in your real context.
回答2:
You could do this via a construtor, where you need to call the base class constructor.
class car {
Public string Name {public get; protected set}
}
That should basically work too.
来源:https://stackoverflow.com/questions/13540196/are-class-initializers-possible-in-c