索引器的扩展方法,它们会好吗?索引器的扩展方法,它们会好吗?
我正在玩一些代码,重新水合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