【问题标题】:DictionaryEntry to user object用户对象的 DictionaryEntry
【发布时间】:2013-07-02 17:05:31
【问题描述】:

我有一个自定义用户对象类 appuser

   public class appuser
    {
        public Int32 ID { get; set; }
        public Int32 ipamuserID { get; set; }
        public Int32 appID { get; set; }
        public Int32 roleID { get; set; }
        public Int16 departmenttypeID { get; set; }
        public generaluse.historycrumb recordcrumb { get; set; }

        public appuser() { }
        public appuser(DataRow dr)
        {
            ID = Convert.ToInt32(dr["AppUserID"].ToString());
            ipamuserID = Convert.ToInt32(dr["IpamUserID"].ToString());
            appID = Convert.ToInt32(dr["AppID"].ToString());
            roleID = Convert.ToInt32(dr["AppRoleID"].ToString());
            departmenttypeID = Convert.ToInt16(dr["AppDepartmentTypeID"].ToString());
            recordcrumb = new generaluse.historycrumb(dr);
        }
        public void appuserfill(DictionaryEntry de, ref appuser _au)
        {
            //Search for key in appuser given by de and set appuser property to de.value
        }
    }

如何在 appuser 对象中设置作为 DictionaryEntry 中的键传递的属性,而不知道键最初是什么?

例如:de.key = ipamuserID,动态查找_au内的属性并设置value = de.value?

【问题讨论】:

  • 可能是,反射

标签: c# asp.net class dictionary properties


【解决方案1】:

从技术上讲,您可以使用反射,但这不是一个好方法 解决方案 - 尝试写入任意属性。 反射的解决方案可能是这样的:

//Search for key in appuser given by de and set appuser property to de.value
public void appuserfill(DictionaryEntry de, ref appuser _au) { // <- There's no need in "ref"
  if (Object.ReferenceEquals(null, de))
    throw new ArgumentNullException("de");
  else if (Object.ReferenceEquals(null, _au))
    throw new ArgumentNullException("_au");

  PropertyInfo pInfo = _au.GetType().GetProperty(de.Key.ToString(), BindingFlags.Instance | BindingFlags.Public);

  if (Object.ReferenceEquals(null, pInfo))
    throw new ArgumentException(String.Format("Property {0} is not found.", de.Key.ToString()), "de");
  else if (!pInfo.CanWrite)
    throw new ArgumentException(String.Format("Property {0} can't be written.", de.Key.ToString()), "de");

  pInfo.SetValue(_au, de.Value);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 2014-11-26
    • 2023-04-08
    相关资源
    最近更新 更多