0

我有这些课程:

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" });

但我不知道如何添加TICollection<T>.

尝试学习泛型和委托。我知道room.Furnitures.Add(Furniture.Chair)效果更好:)

4

2 回答 2

1
public static void Assign<T>(this IRoom room, Func<IRoom, ICollection<T>> collectionSelector, T itemToAdd)
{
    collectionSelector(room).Add(itemToAdd);
}
于 2013-08-18T12:28:34.333 回答
1

你不需要Func<IRoom,ICollection<T>>这里。这需要空间作为参数并返回ICollection<T>ICollection<T>作为参数就足够了。让我们按照以下方式重写您的代码以使其工作。

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>();
}
于 2013-08-18T12:30:02.450 回答