我怎样才能从班级中获取真正的财产

时间:2016-02-09 11:48:47

标签: c#

我有一个有6个属性的类:

public class ControllerValuesArgs:EventArgs
    {
        // debouncer for button
        private static int btnCounter = 0;
        // flag to send buttons
        bool activeFlag = false;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public ControllerValuesArgs()
        {
            // Reset buttons to initial state
            ResetButtons();
        }

        /// <summary>
        /// Gets or sets state of button 1.
        /// </summary>
        public bool Button1Pressed
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets state of button 2.
        /// </summary>
        public bool Button2Pressed
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets state of button 3.
        /// </summary>
        public bool Button3Pressed
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets state of button 4.
        /// </summary>
        public bool Button4Pressed
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets state of button 5.
        /// </summary>
        public bool Button5Pressed
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets state of button 6.
        /// </summary>
        public bool Button6Pressed
        {
            get;
            set;
        }

我想在内部使用带有true结果的属性将其放入哈希表并转换为字符串。 我尝试了什么:

 /// <summary>
        /// Handler listening on Conontroller variables needed to calculate the expression.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">An object that contains no event data.</param>
        public void ConontrollerValuesUpdate(object sender, EventArgs e)
        {
            ControllerValuesArgs conontrollerValuesArgs = new ControllerValuesArgs();

            hashtable["UserInput"] = conontrollerValuesArgs.ToString();
            CalculateExpression();
        }

我如何调用ore来搜索该类中所有属性的真实结果并将其放入表中?

1 个答案:

答案 0 :(得分:2)

这类似于将任何对象转换为ExpandoObject,因为ExpandObject实现了IDictionary&lt; string,object&gt;。

这应该给你带有属性的字典。

public static class DynamicExtensions
{
   public static IDictionary<string, object> ToDynamicDictionary(this object value)
    {
        IDictionary<string, object> expando = new ExpandoObject();

        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
            expando.Add(property.Name, property.GetValue(value));

        return expando;
    }
}

根据http://blog.jorgef.net/2011/06/converting-any-object-to-dynamic.html

回答