How to access property of anonymous type in C#?

后端 未结 5 1062
南旧
南旧 2020-11-28 02:40

I have this:

List nodes = new List(); 

nodes.Add(
new {
    Checked     = false,
    depth       = 1,
    id          = \"div_\"         


        
      
      
      
5条回答
  •  渐次进展
    2020-11-28 02:56

    Recently, I had the same problem within .NET 3.5 (no dynamic available). Here is how I solved:

    // pass anonymous object as argument
    var args = new { Title = "Find", Type = typeof(FindCondition) };
    
    using (frmFind f = new frmFind(args)) 
    {
    ...
    ...
    }
    

    Adapted from somewhere on stackoverflow:

    // Use a custom cast extension
    public static T CastTo(this Object x, T targetType)
    {
       return (T)x;
    }
    

    Now get back the object via cast:

    public partial class frmFind: Form
    {
        public frmFind(object arguments)
        {
    
            InitializeComponent();
    
            var args = arguments.CastTo(new { Title = "", Type = typeof(Nullable) });
    
            this.Text = args.Title;
    
            ...
        }
        ...
    }
    

提交回复
热议问题