If I have a class defined like this:
public class className
{
public object this[string propertyName]
{
get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
}
public string Foo{ get; set; }
public string Bar { get; set; }
I can of course set and get the values like this:
className d = new className();
d["Foo"]="abcd" // set
string s = (string)f["Bar"];
(thanks to Eduardo Cuomo for his answer here)
But what I'd really like to do is something like:
Type target = Type.GetType(DocumentType);
// loop through list of key-value pairs and populate the data class defined in target object Type
foreach (Dictionary<string, string> PQList in LPQReq)
{
foreach (KeyValuePair<string, string> kvp in PQList)
{
// populate the member in the data class with the value from the MQ String
target[kvp.Key] = kvp.Value;
}
but this wouldn't compile as Cannot apply indexing with [] to an expression of type 'System.Type'
so how could I do that?
I can use dynamic
of course, but maybe there is a way to cast my Type to my target Class?
Aucun commentaire:
Enregistrer un commentaire