问题描述
我是 C# 开发新手,我正在尝试从更多模型的字典中读取所有 PropertyInfo
这是理论:
- 声明一个字典
- 当前类型键存储为字符串,然后存储相应的 PropertyInfos。
- 如果字典为空,则初始化。
- 之后,我使用 GetType() 获取当前类型。
- 检查字典是否包含这个键。如果密钥不存在,则会添加新条目。
人物模型
/// <summary>
/// The firstname of the person.
/// </summary>
[required(AllowEmptyStrings = false,ErrorMessage = "First name must not be empty.")]
[MaxLength(20,ErrorMessage = "Maximum of 20 characters is allowed.")]
public string FirstName { get; set; }
/// <summary>
/// The lastname of the person.
/// </summary>
[required(AllowEmptyStrings = false,ErrorMessage = "Last name must not be empty.")]
[MaxLength(30,ErrorMessage = "Maximum of 30 characters is allowed.")]
public string LastName { get; set; }
/// <summary>
/// The city where the person is living
/// </summary>
[required(AllowEmptyStrings = false,ErrorMessage = "City must not be empty.")]
public string City { get; set; }
城市模型
/// <summary>
/// unique ID at the database
/// </summary>
[required(AllowEmptyStrings = false,ErrorMessage = "City identifier must not be empty.")]
public string CityID { get; set; }
/// <summary>
/// The city where the person is living
/// </summary>
[required(AllowEmptyStrings = false,ErrorMessage = "City must not be empty.")]
public string City { get; set; }
基础模型
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(getPropertyInfos.GetType().Name))
{
Dictionary<string,object> addResult2Dictionary = listPropertyInfo.ToDictionary(propertyInfo => propertyInfo.Name,propertyInfo => propertyInfo.GetValue(getPropertyInfos));
}
return getPropertyInfos;
}
有人知道我还能做什么吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)