2013-08-18 96 views
0

我有這些類:如何使用泛型委託在C#

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)作品更好:)

回答

1
public static void Assign<T>(this IRoom room, Func<IRoom, ICollection<T>> collectionSelector, T itemToAdd) 
{ 
    collectionSelector(room).Add(itemToAdd); 
} 
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>(); 
}