代码之家  ›  专栏  ›  技术社区  ›  TomHastjarjanto

在linqtosql中,是否有一种更短的方法将属性解析为int(或任何其他基元)

  •  1
  • TomHastjarjanto  · 技术社区  · 15 年前

    我基本上想知道是否可以优化此代码:

    AmountComments = Int32.Parse(r.Attribute("AmountComments").Value)
    

    理想情况下我想写一些

    AmountComments = r.Attribute("AmountComments")
    

    R 将是一个Xelement类型的XML标记,它在Linq查询中以前被选中。

    1 回复  |  直到 15 年前
        1
  •  6
  •   TomHastjarjanto    15 年前

    考虑为以下类型编写扩展方法: .Attribute()

    每种类型都有一个扩展方法。这样你就可以:

    AmountComments = r.Attribute("AmountComments").ToInt32();
    
    
    public static class LinqUtils
    {
        public static int Int32(this XAttribute attribute)
        {
            return System.Int32.Parse(attribute.Value);
        }
    }