質問

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.

役に立ちましたか?

解決

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"));

他のヒント

 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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top