1

Is there an easy way to create a class method for a subclass of a DyanamicObject or ExpandoObject?

Is resorting back to reflection the only way?

What I mean is something like :-

class Animal : DynamicObject {
}

class Bird : Animal {
}

class Dog : Animal {
}

Bird.Fly = new Action (()=>Console.Write("Yes I can"));

Bird.Fly in this case applying to the class of Bird rather than any specific instance.

4
  • It's not clear what you are trying to achieve. Please try to rephrase your question. I don't see how a method in a subclass and reflection are related. Commented Aug 21, 2012 at 14:24
  • 1
    ExpandoObject is sealed, anyway... Commented Aug 21, 2012 at 14:24
  • 1
    Your question is very unclear. What do you mean on "class method"? Can you provide an example with some sample code? Commented Aug 21, 2012 at 14:24
  • 1
    Ok, they're called static methods usually. You'll probably be able to expand this. Commented Aug 21, 2012 at 14:38

2 Answers 2

2

Nope, there are no dynamic class scoped methods. The closest thing you could do is have a dynamic singleton statically declared on the subclass.

class Bird : Animal {
    public static readonly dynamic Shared = new ExpandoObject();


}

Bird.Shared.Fly = new Action (()=>Console.Write("Yes I can"));
Sign up to request clarification or add additional context in comments.

Comments

1
 public class Animal : DynamicObject
    {
        Dictionary<string, object> dictionary = new Dictionary<string, object>();

        public override bool TryGetMember(
        GetMemberBinder binder, out object result)
        {
            string name = binder.Name.ToLower();
            return dictionary.TryGetValue(name, out result);
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            dictionary[binder.Name.ToLower()] = value;
            return true;
        }
    }
    public class Bird : Animal
    {

    }

And then call it as your example:

dynamic obj = new Bird();
            obj.Fly = new Action(() => Console.Write("Yes I can"));

            obj.Fly();

For more info check DynamicObject

1 Comment

You demonstrate how to add a method to an instance, however, the op asked for a way to add a method to a class definition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.