索引器的扩展方法,它们会很好吗?
我正在尝试一些重新生成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