不继承List
但是,可以通过创建一个扩展方法来实现对List
以下是一个示例代码,演示了如何通过扩展方法对List
using System;
using System.Collections.Generic;
public static class ListExtensions
{
public static List operator +(List list, T item)
{
list.Add(item);
return list;
}
}
public class Program
{
public static void Main(string[] args)
{
List numbers = new List { 1, 2, 3 };
numbers = numbers + 4;
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
在上述代码中,我们创建了一个扩展方法operator +
,该方法将一个元素添加到List
需要注意的是,扩展方法必须被定义在一个静态类中,并且该类必须是静态的。扩展方法的定义需要使用this
关键字指定对哪个类型进行扩展,这里扩展的类型是List
通过创建扩展方法,我们可以在不继承List