有没有一种简单的方法来为DyanamicObject或ExpandoObject的子类创建类方法?
求助于反思是唯一的方法吗?
我的意思是这样的:
class Animal : DynamicObject {
}
class Bird : Animal {
}
class Dog : Animal {
}
Bird.Fly = new Action (()=>Console.Write("Yes I can"));本例中的Bird.Fly应用于鸟的类,而不是任何特定的实例。
发布于 2012-08-22 22:08:08
不,没有动态的类作用域方法。你能做的最接近的事情就是在子类上静态声明一个动态单例。
class Bird : Animal {
public static readonly dynamic Shared = new ExpandoObject();
}
Bird.Shared.Fly = new Action (()=>Console.Write("Yes I can"));发布于 2012-08-21 23:44:02
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
https://stackoverflow.com/questions/12056971
复制相似问题