samedi 3 avril 2021

Get PropertyInfos from more Models. i.e. PersonModel, DeparmentModel, etc. in a Dictionary (C#)

i'm new in C# development, i`m trying to read all PropertyInfo in a dictionary from more Models

this is the teory:

  • Declacate a Distionary<string, List>
  • Current Type key is stored as string and then corresponding PropertyInfos.
  • If the dictionary is null, it is initialized.
  • Afterwards I get the current type with GetType().
  • Check if the dictionary contains this key. If the key is not a new entry is added.

but my code isn't working, please could you help me?

private static readonly Dictionary<string, List<PropertyInfo>> getPropertyInfos = new Dictionary<string, List<PropertyInfo>>();

    /// <summary>
    /// defines Dictionary<string, List<PropertyInfo>> for PropertyInfos
    /// </summary>
    private static Dictionary<string, List<PropertyInfo>> GetPropertyInfos()
    {
    // Dictionary will be initilized
        List<PropertyInfo> listPropertyInfo = getPropertyInfos.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
                                           .Where(prop => prop.IsDefined(typeof(RequiredAttribute), true) || prop.IsDefined(typeof(MaxLengthAttribute), true))
                                           .ToList();
        if (!getPropertyInfos.ContainsKey(propertyInfo => propertyInfo.Name))
        {
            Dictionary<string, object> addResult2Dictionary = listPropertyInfo.ToDictionary(propertyInfo => propertyInfo.Name, propertyInfo => propertyInfo.GetValue(getPropertyInfos));
        }
        return getPropertyInfos;
    }




Aucun commentaire:

Enregistrer un commentaire