2009-03-01 24 views
22

索引器的擴展方法,它們會好嗎?索引器的擴展方法,它們會好嗎?

我正在玩一些代碼,重新水合POCO的。

代碼遍歷從SqlDataReader返回的行,並使用反射從列值中分配屬性。在我的調用堆棧中,我有一行代碼,如下所示: -

poco.Set("Surname", "Smith"); // uses extension method ... 

Set方法是作爲擴展方法編寫的。

這將是巨大的,已經能夠像這樣寫代碼

poco["Surname"] = "Smith"; // extension methods for indexers ? 

即我想寫索引擴展方法

是否有很好的理由.NET不具備擴展方法索引器? 其他人對擴展方法索引器有其他好處嗎?

順便說一句... 如果我們可以編寫擴展方法索引那麼我們就可以這樣寫代碼...

var poco = PocoFactory(); 
    poco.Surname = 「Smith」; // is this JavaScript ... 
    poco[Surname] = 「Smith」 ; // … or is this c# or both 

從我的代碼的某些代碼段

///////////////////////////////////////////// 
// Client calling code 
IDab dab = DabFactory.Create("Northwind"); 
string sql = @"select * from Customers "; 
var persons = dab.ExecuteReader<NorthwindCustomer>(sql); 
if (dab != null{ 
    Assert.That(persons[0].CustomerID , Is.EqualTo("ALFKI"));} 
///////////////////////////////////////////// 
List<T> IDab.ExecuteReader<T>(string commandText) 
{ 
    List<T> pocos = new List<T>(); 
    // setup connection 
    SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); 
    while (reader.Read()) 
    { 
      Dictionary<string, int> colMappings = null ; 
      if (colMappings == null){ 
       colMappings = reader.GetSqlDataReaderColumnMappings();} 
      T poco = new T(); 
      poco.DbToMem<T>(reader, colMappings); 
      pocos.Add(poco); 
     } 
    } 
    // connection cleanup ... 
    return pocos ; 
} 

// the set extension method signature 
public static void Set<T>(this T thisClientObject, string thisPropertyName, object newValue) where T : class 

回答

11

索引器分享了很多與屬性的共性(引擎蓋下,索引器具有索引的屬性),並且擴展屬性不存在。同意,會有方便的場景。

重新提供的場景 - 在某些方面,這與dynamic非常相似。當然,如果你聲明一個接口一個字符串索引器,那麼你的閱讀器代碼可以直接使用它 - 但它會是一個不必要的工作來重複實現這個接口!

Re擴展方法;這是否使用常規反射?你可能想看看如HyperDescriptor這樣的技巧,如果你正在做很多這些,可能會節省很多CPU時間。然後典型用法是:

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); 
while (reader.Read()) 
{ 
    T poco = new T(); 
    // abbreviated... 
    (per prop) 
     props[propName].SetValue(poco, cellValue); 
} 

您可以通過查看第一個返回的列(每一次電網,而不是每行),並且僅訪問匹配列進一步優化這個...

或者,看看ORM工具; Expression也可以用來做數據讀取(我有一個完整的例子在usenet上的這個地方,爲DbLinq)

+0

有趣的感謝,我會看看。 – judek 2009-03-01 15:58:42

-1

爲了重新保溼Pocos,我建議看看AutoMapper Nuget包。它非常簡單,大大減少了代碼量。