How can I pass a property as a delegate?

前端 未结 6 1598
深忆病人
深忆病人 2021-02-04 04:03

This is a theoretical question, I\'ve already got a solution to my problem that took me down a different path, but I think the question is still potentially interesting.

6条回答
  •  春和景丽
    2021-02-04 04:54

    Worth mentioning you can do this with some reflection trickery.. something like...

    public static void LoadFromReader(this object source, SqlDataReader reader, string propertyName, string fieldName)
        {
            //Should check for nulls..
            Type t = source.GetType();
            PropertyInfo pi = t.GetProperty(propertyName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            object val = reader[fieldName];
            if (val == DBNull.Value)
            {
                val = default(T);
            }
            //Try to change to same type as property...
            val = Convert.ChangeType(val, pi.PropertyType);
            pi.SetValue(source, val, null);
        }
    

    then

    myClass.LoadFromReader(reader,"Property1","field1");
    

提交回复
热议问题