扩展C#List.Last

blo*_*oop 1 c# extension-methods arraylist

Lists的.Last()方法仅返回一个值.我希望能够做到这样的事情.

  List<int> a = new List<int> { 1, 2, 3 };
  a.Last() = 4;
Run Code Online (Sandbox Code Playgroud)

这是我尝试编写扩展方法(它不编译)

public unsafe static T* mylast<T>(this List<T> a)
{
   return &a[a.Count - 1];
}
Run Code Online (Sandbox Code Playgroud)

我想做什么?

编辑:

这是我想要使用它的一个例子.

 shapes.last.links.last.points.last = cursor;   //what I want the code to look like
 //how I had to write it.
 shapes[shapes.Count - 1].links[shapes[shapes.Count - 1].links.Count - 1].points[shapes[shapes.Count - 1].links[shapes[shapes.Count - 1].links.Count - 1].points.Count-1] = cursor;
Run Code Online (Sandbox Code Playgroud)

这就是做的原因

shapes[shapes.Count-1] 
Run Code Online (Sandbox Code Playgroud)

不是一个真正的解决方案.

Tho*_*ith 7

只是用

a[a.Count-1] = 4;
Run Code Online (Sandbox Code Playgroud)

或者写一个扩展方法

a.SetLast(4);
Run Code Online (Sandbox Code Playgroud)

即使你可以创建一个虚假扩展属性,它也不是一个好主意.如果解决方案涉及不安全的代码,则会增加一倍.


ole*_*sii 5

C#中没有扩展属性.但是这里有一个可以使用的扩展方法:

public static class ListEx
{
    public static void SetLast<T>(this IList<T> list, T value)
    {
        if (list == null)
            throw new ArgumentNullException("list");
        if(list.Count == 0)
            throw new ArgumentException(
                "Cannot set last item because the list is empty");

        int lastIdx = list.Count - 1;
        list[lastIdx] = value;
    }

    //and by symmetry
    public static T GetLast<T>(this IList<T> list)
    {
        if (list == null)
            throw new ArgumentNullException("list");
        if (list.Count == 0)
            throw new ArgumentException(
                "Cannot get last item because the list is empty");

        int lastIdx = list.Count - 1;
        return list[lastIdx];
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是如何使用它

class Program
{
    static void Main(string[] args)
    {
        List<int> a = new List<int> { 1, 2, 3 };
        a.SetLast(4);
        int last = a.GetLast(); //int last is now 4
        Console.WriteLine(a[2]); //prints 4
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要,可以调整验证行为.