简体   繁体   中英

Match Strings to Class Properties

I need to match the properties of the FixedFormatSettings . For example, I may have the strings "BitmapUnembeddableFonts" and "UsePdaA" in a string[]. If I wanted to loop through the string[], and set any matching property I find (as a string) to true (eg FixedFormatSettings.UsePdaA = true), how would I go about doing that?

Use next code as an example of setting properties by having a dictionary of names and their values.

var valuesToSet = new Dictionary<string, object> 
                  {
                        {"BitmapUnembeddableFonts", false}, 
                        {"UsePdaA", true}
                  };

var settings = new FixedFormatSettings();

var properties = settings.GetType()
                         .GetProperties()
                         .Where(p => p.CanWrite);

foreach (var property in properties)
{
    object valueToSet;
    if(valuesToSet.TryGetValue(property.Name, out valueToSet))
    {
        property.SetValue(settings, valueToSet);
    }
}

Console.WriteLine(settings.BitmapUnembeddableFonts); //false
Console.WriteLine(settings.UsePdaA); //true

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