T4格式化生成的属性

时间:2013-09-25 08:40:07

标签: c# t4

这是我的T4模板方法来生成属性

public string Property(EdmProperty edmProperty)
{
    var fieldName = String.Format(CultureInfo.InvariantCulture,"_{0}{1}",_code.Escape(edmProperty).Substring(0,1).ToLower(),_code.Escape(edmProperty).Substring(1));
    var propertyType = _typeMapper.GetTypeName(edmProperty.TypeUsage);
    return string.Format(
        CultureInfo.InvariantCulture,
        @"{0} {1} {2} {6}{{{6}{3} get{{ return {4}; }}{6}{5} set{{ {4} = value; }}{6} }}",
        Accessibility.ForProperty(edmProperty),
        propertyType,
        _code.Escape(edmProperty),
        _code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
        fieldName,
        _code.SpaceAfter(Accessibility.ForSetter(edmProperty)),
        "");
}

生成的代码格式如下:

public string SomeProperty{ get{ return _someProperty; } set{ _someProperty = value; }}

我想将其格式化,使其显示如下:

public string SomeProperty
{
     get{ return _someProperty; }
     set{ _someProperty = value; }
}

我尝试在例如String.Format)中创建{6}的最后一个参数:

  1. Environment.NewLine
  2. "\r\n"
  3. "\n"
  4. 我也知道自动实现的属性,但需要这样做。

    那么这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

Enviroment.NewLine应该是正确的。它应该是这样的:

return string.Format(
    CultureInfo.InvariantCulture,
    @"{0} {1} {2} {6}{{{6}{3} get{{ return {4}; }}{6}{5} set{{ {4} = value; }}{6} }}",
    Accessibility.ForProperty(edmProperty),
    propertyType,
    _code.Escape(edmProperty),
    _code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
    fieldName,
    _code.SpaceAfter(Accessibility.ForSetter(edmProperty)),
    Environment.NewLine);