简体   繁体   中英

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 more 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM