1

DyanamicObjectまたはExpandoObjectのサブクラスのクラスメソッドを作成する簡単な方法はありますか?

振り返りに頼るのが唯一の方法ですか?

私が言いたいのは:-のようなものです

class Animal : DynamicObject {
}

class Bird : Animal {
}

class Dog : Animal {
}

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

この場合、Bird.Flyは、特定のインスタンスではなく、Birdのクラスに適用されます。

4

2 に答える 2

2

いいえ、動的クラススコープのメソッドはありません。最も近い方法は、動的なシングルトンをサブクラスで静的に宣言することです。

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


}

Bird.Shared.Fly = new Action (()=>Console.Write("Yes I can"));
于 2012-08-22T14:08:07.540 に答える
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
    {

    }

そして、あなたの例としてそれを呼び出します:

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

            obj.Fly();

詳細については、DynamicObjectを確認してください

于 2012-08-21T15:44:02.187 に答える