是否有一种简单的方法可以为DyanamicObject或ExpandoObject的子类创建类方法?
唯一的方法是回归反思吗?
我的意思是: -
class Animal : DynamicObject {
}
class Bird : Animal {
}
class Dog : Animal {
}
Bird.Fly = new Action (()=>Console.Write("Yes I can"));
Bird.Fly在这种情况下应用于Bird类而不是任何特定实例。
答案 0 :(得分:2)
不,没有动态类范围的方法。你能做的最接近的事情是在子类上静态声明一个动态单例。
class Bird : Animal {
public static readonly dynamic Shared = new ExpandoObject();
}
Bird.Shared.Fly = new Action (()=>Console.Write("Yes I can"));
答案 1 :(得分:0)
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