문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top