如何在C#中使用泛型委托
本文关键字:泛型 | 更新日期: 2023-09-27 18:28:00
我有这些类:
public interface IPerson
{
string Name { get; set; }
}
public class Person : IPerson
{
public string Name { get; set; }
}
public interface IRoom
{
List<Furniture> Furnitures { get; set; }
List<Person> People { get; set; }
}
public class Room : IRoom
{
public List<Furniture> Furnitures { get; set; }
public List<Person> People { get; set; }
}
public enum Furniture
{
Table,
Chair
}
我有这个扩展方法:
public static void Assign<T>(this IRoom sender, Func<IRoom,ICollection<T>> property, T value)
{
// How do I actually add a Chair to the List<Furniture>?
}
我想这样使用它:
var room = new Room();
room.Assign(x => x.Furnitures, Furniture.Chair);
room.Assign(x => x.People, new Person() { Name = "Joe" });
但是我不知道如何将T
添加到ICollection<T>
。
尝试学习泛型和委托。我知道room.Furnitures.Add(Furniture.Chair)
效果更好:)
public static void Assign<T>(this IRoom room, Func<IRoom, ICollection<T>> collectionSelector, T itemToAdd)
{
collectionSelector(room).Add(itemToAdd);
}
此处不需要Func<IRoom,ICollection<T>>
。这将占用空间作为参数,并返回ICollection<T>
。CCD_ 6作为一个参数就足够了。让我们按照以下方式重写您的代码以使其正常工作。
public static void Assign<T>(this IRoom sender, ICollection<T> collection, T value)
{
collection.Add(value);
}
然后称之为
room.Assign(room.Furnitures, Furniture.Chair);
room.Assign(room.People, new Person() { Name = "Joe" });
如果你对这种方法不满意,你只需要自己的方法,那么试试下面的
public static void Assign<T>(this IRoom sender, Func<IRoom, ICollection<T>> property, T value)
{
property(sender).Add(value);
}
然后用你自己的语法调用它应该可以
room.Assign(x => x.Furnitures, Furniture.Chair);
room.Assign(x => x.People, new Person() { Name = "Joe" });
注意:请记住,您尚未初始化集合,这将导致NullReferenceException
,因此为了消除它,请在Room
类中添加一个构造函数,如下所示
public Room()
{
Furnitures = new List<Furniture>();
People = new List<Person>();
}