インデクサーの拡張メソッド、それらは良いでしょうか?
私はPOCOを再水和するいくつかのコードで遊んでいました。
このコードは、SqlDataReaderから返された行を繰り返し処理し、リフレクションを使用して列の値からプロパティを割り当てます。コールスタックの下に、次のようなコードがありました:-
poco.Set("Surname", "Smith"); // uses extension method ...
Setメソッドは拡張メソッドとして作成されました。
このようなコードを書くことができたら素晴らしいと思います
poco["Surname"] = "Smith"; // extension methods for indexers ?
つまり、インデクサーの拡張メソッドを書きたかったのです。
.Netにインデクサーの拡張メソッドがない理由はありますか?他の人は拡張メソッドインデクサーの他の良い使い方を持っていますか?
余談ですが...インデクサーの拡張メソッドを記述できれば、次のようなコードを記述できます…</ p>
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