Dynamically set the property name of a C# anonymous type

后端 未结 6 1950
一向
一向 2020-12-19 02:28

Is there any way to dynamically set the property name of an anonymous type?

Normally we\'d do like this:

var anon = new { name = \"Kayes\" };
         


        
相关标签:
6条回答
  • 2020-12-19 02:29

    As has been mentioned, you can't change the property name; how would you code against it, for example? However, if this is for data-binding, you can do some tricks to bend the display name of properties at runtime - for example ICustomTypeDescriptor/TypeDescriptionProvider (and a custom PropertyDescriptor).

    Lots of work; it would need to really be worth it...

    Another option is a custom attribute:

    using System;
    using System.ComponentModel;
    using System.Windows.Forms;
    class MyDisplayNameAttribute : DisplayNameAttribute {
        public MyDisplayNameAttribute(string value) : base(value) {}
        public override string DisplayName {
            get {
                return @"/// " + base.DisplayNameValue + @" \\\";
            }
        }
    }
    class Foo {
        [MyDisplayName("blip")]
        public string Bar { get; set; }
        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            using (Form form = new Form {
                Controls = {
                    new PropertyGrid {
                        Dock = DockStyle.Fill,
                        SelectedObject = new Foo { Bar = "abc"}}
                }
            }) {
                Application.Run(form);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-19 02:32

    Not without a massive amount of reflection, probably moreso than you're interested in leveraging for what you're doing. Perhaps you should look into instead using a Dictionary, with the key value being the property name.

    0 讨论(0)
  • 2020-12-19 02:39

    Nope. You want do construct a static structure from dynamic information. Won't work, think about it. Use a dictionary for your case.

    0 讨论(0)
  • 2020-12-19 02:43

    The compiler must know about the property name, otherwise it can't create the anonymous type for you.

    So, no, this isn't possible, unless the actual property name is known at compile-time (through some VS-generated magic with the database or something).

    0 讨论(0)
  • 2020-12-19 02:55

    Dynamic properties can be done with compiling code at runtime but this would be overkill for your needs I guess...

    0 讨论(0)
  • 2020-12-19 02:56

    That is not possible because even though the type is anonymous, it is not a dynamic type. It is still a static type, and properties about it must be known at compile time.

    You might want to check out the .NET 4.0 "dynamic" keyword for generating true dynamic classes.

    0 讨论(0)
提交回复
热议问题