C# Extension Method for Object

后端 未结 6 1905
萌比男神i
萌比男神i 2021-02-06 22:22

Is it a good idea to use an extension method on the Object class?

I was wondering if by registering this method if you were incurring a performance penalty as it would b

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 23:18

    The following example demonstrates the extension method in use.

    namespace NamespaceName
    {
    public static class CommonUtil
    {
        public static string ListToString(this IList list)
        {
            StringBuilder result = new StringBuilder("");
    
            if (list.Count > 0)
            {
                result.Append(list[0].ToString());
                for (int i = 1; i < list.Count; i++)
                    result.AppendFormat(", {0}", list[i].ToString());
            }
            return result.ToString();
        }
      }
    }
    

    The following example demonstrates how this method can be used.

    var _list = DataContextORM.ExecuteQuery("Select name from products").ToList();
    string result = _list.ListToString();
    

提交回复
热议问题