开发者

Delegating to properties in C#

I'm doing something with an Odbc DataReader. Each row in a query result should be transformed into a ResultObject looking like this:

struct ResultObject {
    public int Prop1 { get; set; }
    public string Prop2 { get; set; }
    ...
}

In order to write mor开发者_运维百科e domain-specific code, I want to transform this code

var query = "SELECT Prop1, Prop2, ... FROM MyTable;";
... connect, submit query
while( reader.Read() ) {
  var fieldValue = fields[ fieldindex ];
  switch( fieldindex ) {
     case( indexProp1 ): result.Prop1.Set( (int) fieldValue); break;
     case( indexProp2 ): result.Prop2.Set( (string) fieldvalue); break;
     ...
  }
}

into something more generic, where I build the mapping between indices and 'setters' dynamically:

But it would be nice to have something even more concise like:

PropMapper mappers[] = {
 new PropMapper("Prop1", ResultType.Prop1 ),
 new PropMapper("Prop2", ResultType.Prop2 ),
 ....
};

I have, however, no clue how to create a PropMapper from the property of a ResultType.

The question:

How can I generate an object that wraps/delegates to a property of a given type?

Note: though ORMs are quite useful for this, I'm really only asking how C# allows for creating the delegate (or anything equivalent)


PropMapper would need to receive a lambda expression as parameter, representing the property. Prism's NotificationObject receives such an expression on its RaisePropertyChanged event.

You can take a look on Prism's source code how the lambda expression is used to extract the property and use it.


You can try to use Reflection:

PropertyInfo[] props = new PropertyInfo[]
{
  typeof(ResultObject).GetProperty("prop1"),
  typeof(ResultObject).GetProperty("prop2"),
};

for (int i = 0; i < props.Length; i++)
{
  props[i].SetValue(result, fieldValue, null);
}


You might want to take a look into a mini-orm like dapper

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜