---
title: "扩展方法中的一个小技巧"
author: "梁利锋"
date: "2008-12-12T00:05:48Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2008-12-12T00:05:48Z"
id: 291116
url: "https://llf.iteye.com/blog/291116"
---

今天写扩展方法，突然想到，其实扩展方法是静态方法，所以它和原有类中的方法是很不同的，对于扩展方法来说，即使对象为空，也是可以正确执行的，比如下面对于字符串数组的扩展方法：

```c#

public static string First(this string[] ss)
{
    if(ss == null || ss.Length == 0)
    {
        return null;
    }
    return ss[0];
}

public static string Last(this string[] ss)
{
    if(ss == null || ss.Length == 0)
    {
        return null;
    }
    return ss[ss.length - 1];
}

```

　　这里检测了对象是否为空，如果为空则也返回空，所以使用它的时候，我们就不会因为调用这两个方法而得到 NullPointException:

```c#

static void Main(string[] args)
{
    string[] ss = null;
    var s = ss.First();
    if(s == null)
    {
        Console.WriteLine("<NULL>");
    }
    else
    {
        Console.WriteLine(s);
    }
    Console.ReadLine();
}

```

　　使用扩展方法，反而可以进一步简化代码，只是不知道会不会让不了解的人在读代码时有些头晕了。