【问题标题】:C# DynamicObject class methodsC# DynamicObject 类方法
【发布时间】:2012-08-22 22:08:07
【问题描述】:

是否有一种简单的方法可以为 DynamicObject 或 ExpandoObject 的子类创建类方法?

求助于反思是唯一的方法吗?

我的意思是:-

class Animal : DynamicObject {
}

class Bird : Animal {
}

class Dog : Animal {
}

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

Bird.Fly 在这种情况下适用于 Bird 类而不是任何特定实例。

【问题讨论】:

  • 不清楚您要达到的目标。请尝试改写您的问题。我看不出子类中的方法和反射是如何相关的。
  • ExpandoObject 是密封的,反正...
  • 你的问题很不清楚。 “类方法”是什么意思?能否提供一些示例代码的示例?
  • 好吧,它们通常被称为静态方法。您可能可以扩展this

标签: c# dynamicobject


【解决方案1】:

不,没有动态类作用域方法。您可以做的最接近的事情是在子类上静态声明一个动态单例。

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


}

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

【讨论】:

    【解决方案2】:
     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

    【讨论】:

    • 您演示了如何将方法添加到实例中,但是操作要求提供一种将方法添加到类定义中的方法。
    猜你喜欢
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    相关资源
    最近更新 更多