lundi 13 mai 2019

PropertyInfo CanWrite is false on a property WITH a setter

I've got a head scratcher here. I'm trying to load my xml .config file into a strongly typed class, something I've done several times before. This time, 27/68 public properties WITH setters I can't write to. I'm totally perplexed.

Here's my AppSettings class (with just 2 properties. The other 66 are just more of the same)

    public class AppSettings
    {
        private AppSettings()
        {
        }

        public static AppSettings AppSettingsInstance = new AppSettings();

        public string WebServiceUrl { get; set; }

        [Required(false)]
        public string StorageLocationCheckIn { get; set; }
 }


Then after some validation, I try to load:

        public void LoadAppSettings(object classInstanceToLoadAppSettingsInto)
        {
            try
            {
                var pis = classInstanceToLoadAppSettingsInto.GetType().GetProperties();
                Dictionary<string, string> GRRRRRRRRRRRRRR = new Dictionary<string, string>();
                foreach (var pi in pis)
                {
                    if (string.IsNullOrEmpty(AppSettings[pi.Name])) continue;
                    if (pi.CanWrite)
                        pi.SetValue(classInstanceToLoadAppSettingsInto, Convert.ChangeType(AppSettings[pi.Name], pi.PropertyType, null));
                    else
                    {
                        GRRRRRRRRRRRRRR.Add(pi.Name, AppSettings[pi.Name]);
                    }
                }
            }
            catch (Exception)
            {
                throw new InvalidOperationException("Failed to load App Settings.  Verify .config and class properties.");
            }          
        }

CanWrite for WebServiceUrl is false CanWrite for StorageLocationCheckIn is true

My angry GRRRR dictionary shows a variety of string and bool properties. I can't figure out a commonality to explain why some of the properties can't be written too.





Aucun commentaire:

Enregistrer un commentaire