索引器的擴展方法,它們會好嗎?索引器的擴展方法,它們會好嗎?
我正在玩一些代碼,重新水合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
有趣的感謝,我會看看。 – judek 2009-03-01 15:58:42