简体   繁体   English

C#DynamicObject类方法

[英]C# DynamicObject class methods

Is there an easy way to create a class method for a subclass of a DyanamicObject or ExpandoObject? 有没有一种简单的方法为DyanamicObject或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. Bird.Fly在这种情况下应用于Bird类而不是任何特定实例。

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 有关更多信息,请检查DynamicObject

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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