简体   繁体   中英

How to change property accessors on runtime

I'm looking for a way to change / add accessors to properties of a given class on runtime. sample code bellow, runs on .ctor of the class, what I want to reach is to add the 'TheSetMethod' to 'set' accessor of each 'field' so by changing the field on runtime. FYI: There's an implementation constraint behind this that makes me do this in this way istead of using standard "get;set;" ancestors, so I can not have 'get;set;' in design time.

    public string field1;

    .ctor()
    {
        Type typeWebConfig = this.GetType();
        MemberInfo[] Fields = typeWebConfig.GetMembers(BindingFlags.Public |
                              BindingFlags.Instance );
        foreach(MemberInfo member in Fields) 
            if(member.MemberType == MemberTypes.Field)
            {
                FieldInfo field = (FieldInfo)member;
                //add a delegate method to field's 'SET'
            }
     }

     void TheSetMethod(string propName)
     {
     }

any help will be appreciated. Cheers

You could implement a custom DynamicObject type to handle the accessors manually. This will only work in .NET 4+ though.

Why not just add the code to the setters to start with and then use a variable to determine if the code should execute or not? This sounds like a poor design in my opinion as making the setter's "Dynamic" also seems like it will not be able to be tested very well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM