The .列表的 Last(( 方法只返回一个值。 我希望能够做这样的事情。
List<int> a = new List<int> { 1, 2, 3 };
a.Last() = 4;
这是我尝试编写扩展方法(它不编译(
public unsafe static T* mylast<T>(this List<T> a)
{
return &a[a.Count - 1];
}
我想做的事情可能吗?
编辑:
这是我想在哪里使用它的一个例子。
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;
这就是为什么做
shapes[shapes.Count-1]
并不是真正的解决方案。
只需使用
a[a.Count-1] = 4;
或者编写扩展方法
a.SetLast(4);
即使你可以创建一个虚假扩展属性,也不是一个好主意。如果解决方案涉及不安全的代码,则此值会加倍。
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];
}
}
这是如何使用它
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
}
}
如果需要,可以调整验证行为。
可以创建设置最后一个元素的扩展方法。
为简单起见,这是没有错误检查时的外观:
public static class ListExtensions
{
public static void SetLast<T>(this IList<T> source, T value)
{
source[source.Count - 1] = value;
}
}
当然,如果你想正确地做到这一点,你还需要错误检查:
public static void SetLast<T>(this IList<T> source, T value)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (source.Count == 0)
{
throw new ArgumentException("cannot be empty", "source");
}
source[source.Count - 1] = value;
}
我推荐 Thom Smith 的解决方案,但如果你真的想拥有类似属性的访问权限,为什么不直接使用属性呢?
public class MyList<T> : List<T>
{
public T Last
{
get
{
return this[this.Count - 1];
}
set
{
this[this.Count - 1] = value;
}
}
}
用于:
var m = new MyList<int> { 1, 2, 3 };
m.Last = 4;
Console.WriteLine(m.Last);
没有不安全的代码,所以更好。 此外,它并不排除使用 LINQ 的 Last
方法(编译器可以根据它们的使用方式区分两者(。
public class AdvancedList : List<int>
{
public int Last
{
get { return this[Count - 1]; }
set
{
if(Count >= 1 )
this[Count - 1] = value;
else
Add(value);
}
}
}
AdvancedList advancedList = new AdvancedList();
advancedList.Add(100);
advancedList.Add(200);
advancedList.Last = 10;
advancedList.Last = 11;
你可能会说: 如果你想设置最后一个值: 更酷的是传递一个新值:
public static void SetLast(this List<int> ints, int newVal)
{
int lastIndex = ints.Count-1;
ints[lastIndex] = newVal;
}