在C#中,泛型是一种强大的特性,它允许你在编译时定义可重用的代码组件,这些组件可以适用于多种数据类型。使用泛型可以提高代码的灵活性、可读性和性能,同时减少代码重复。
以下是在C#中使用泛型的基本步骤:
public class GenericClass<T>
{
public T Data { get; set; }
public void PrintData()
{
Console.WriteLine(Data);
}
}
public interface IRepository<T>
{
void Add(T item);
T GetById(int id);
}
public T GenericMethod<T>(T param)
{
return param;
}
GenericClass<int> intClass = new GenericClass<int>();
intClass.Data = 10;
intClass.PrintData(); // 输出: 10
GenericClass<string> stringClass = new GenericClass<string>();
stringClass.Data = "Hello, World!";
stringClass.PrintData(); // 输出: Hello, World!
public class Repository<T> : IRepository<T>
{
private List<T> _items = new List<T>();
public void Add(T item)
{
_items.Add(item);
}
public T GetById(int id)
{
// 简单示例,实际应用中可能需要更复杂的逻辑
return _items.FirstOrDefault(i => i.GetHashCode() == id);
}
}
IRepository<int> intRepo = new Repository<int>();
intRepo.Add(1);
intRepo.Add(2);
Console.WriteLine(intRepo.GetById(1)); // 输出: 1
int result = GenericMethod<int>(5); // 输出: 5
string strResult = GenericMethod<string>("Hello"); // 输出: Hello
你可以使用约束来限制泛型类型参数的类型。常见的约束包括:
where T : class
:T必须是引用类型。where T : struct
:T必须是值类型。where T : new()
:T必须有一个无参数的构造函数。where T : BaseClass
:T必须是BaseClass的派生类。where T : IInterface
:T必须实现IInterface接口。public class GenericClassWithConstraint<T> where T : new()
{
public T CreateInstance()
{
return new T();
}
}
GenericClassWithConstraint<MyClass> myClassInstance = new GenericClassWithConstraint<MyClass>();
MyClass obj = myClassInstance.CreateInstance();
C#标准库提供了许多泛型集合类,如List<T>
、Dictionary<TKey, TValue>
等。
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Dictionary<string, int> ageMap = new Dictionary<string, int>
{
{ "Alice", 30 },
{ "Bob", 25 }
};
foreach (var pair in ageMap)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
通过这些步骤,你可以在C#中有效地使用泛型来编写灵活且可重用的代码。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。