在C#中类初始化可能吗? [英] Are class initializers possible in C#?

查看:160
本文介绍了在C#中类初始化可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中你有对象初始化初始化对象在创建时的领域,而无需使用构造



现在我想知道如果有一个相当于类,这意味着定义子类时,实际上不就可以初始化的类的属性。使用替代语法,但只是述说一个已知属性的值为



例如:



<预类=郎-CS prettyprint-覆盖> 公共抽象类车{
公共抽象的字符串名称{; }
}
//通常的做法
公共类野马:汽车{
公众覆盖字符串名称{{返回福特野马; }}
}
//我避免了主意样板代码
公共类野马:汽车{名称=福特野马}

有没有办法做到这一点?如果没有,可能T4模板是任何帮助吗?


解决方案

为使rekire的例子更清晰,你会喜欢写东西

 公共抽象类汽车
{
公共字符串名称{;私人集; }

保护汽车(字符串名称)
{
this.Name =名称;
}
}

公共类野马:汽车
{
公共野马():基地(野马)
{
}
}

编辑:另一种选择是使用属性,在那里你会写:

  [CarName(野马)] 
公共类野马:汽车

...具有编写相应的反射代码。我的强烈的建议你不要但。当然,属性可能在你的真正的上下文。


有用

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.

这篇关于在C#中类初始化可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆