从DynamicObject继承

从DynamicObject继承

本文介绍了C#4.0:动态,从DynamicObject继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我有这个:

dynamic foo = new Foobar();

我有这个:

public class Foobar : DynamicObject
{

}

问题是,是否可以重写 DynamicObject 的成员,以便此代码:

The question is, is it possible to override members of DynamicObject so that this code:

string name = new Foobar().Name

在运行时是否抛出 Exception ?如果 Name 不是成员,我想为 name 返回 default .

Does not throw an Exception at run-time? I want to return default for name's if Name is not a member.

可能吗?我需要覆盖什么?

Possible? What do I need to override?

推荐答案

覆盖TryGetMember(和TrySetMember).从DynamicObject类派生的类可以重写此方法,以指定操作的动态行为,例如获取属性的值.

Override TryGetMember (and TrySetMember). Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as getting a value for a property.

http://msdn.microsoft.com/zh-我们/library/system.dynamic.dynamicobject.aspx http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember.aspx

这篇关于C#4.0:动态,从DynamicObject继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:43