DynamicObject 类使您能够定义可以动态对象上执行哪些操作以及如何执行这些操作。 例如,可以定义当尝试获取或设置对象属性、调用一个方法或执行标准的数学运算(如加法和乘法)时将发生的情况。
如果要为库创建更方便的协议,此类可能非常有帮助。 例如,如果库用户必须使用 Scriptobj.SetProperty("Count", 1) 这样的语法,您可以允许使用更简单的语法,如scriptobj.Count = 1。
无法直接创建 DynamicObject 类的实例。 若要实现动态行为,您可能需要继承自 DynamicObject 类并重写必要方法。 例如,如果只需要设置和获取属性的操作,您可以只覆盖 TrySetMember 和 TryGetMember 方法。
在 C# 中,要为从 DynamicObject 类派生的类实例启用动态行为,必须使用 dynamic 关键字。 有关详细信息,请参阅使用类型 dynamic(C# 编程指南)。
在 Visual Basic 中,后期绑定支持动态操作。 有关详细信息,请参阅早期绑定和后期绑定 (Visual Basic)。
下面的代码示例演示如何创建从 DynamicObject 类派生的类的实例。
// The class derived from DynamicObject. public class DynamicDictionary : DynamicObject { // The inner dictionary. Dictionary<string, object> dictionary = new Dictionary<string, object>(); // This property returns the number of elements // in the inner dictionary. public int Count { get { return dictionary.Count; } } // If you try to get a value of a property // not defined in the class, this method is called. public override bool TryGetMember( GetMemberBinder binder, out object result) { // Converting the property name to lowercase // so that property names become case-insensitive. string name = binder.Name.ToLower(); // If the property name is found in a dictionary, // set the result parameter to the property value and return true. // Otherwise, return false. return dictionary.TryGetValue(name, out result); } // If you try to set a value of a property that is // not defined in the class, this method is called. public override bool TrySetMember( SetMemberBinder binder, object value) { // Converting the property name to lowercase // so that property names become case-insensitive. dictionary[binder.Name.ToLower()] = value; // You can always add a value to a dictionary, // so this method always returns true. return true; } } class Program { static void Main(string[] args) { // Creating a dynamic dictionary. dynamic person = new DynamicDictionary(); // Adding new dynamic properties. // The TrySetMember method is called. person.FirstName = "Ellen"; person.LastName = "Adams"; // Getting values of the dynamic properties. // The TryGetMember method is called. // Note that property names are case-insensitive. Console.WriteLine(person.firstname + " " + person.lastname); // Getting the value of the Count property. // The TryGetMember is not called, // because the property is defined in the class. Console.WriteLine( "Number of dynamic properties:" + person.Count); // The following statement throws an exception at run time. // There is no "address" property, // so the TryGetMember method returns false and this causes a // RuntimeBinderException. // Console.WriteLine(person.address); } } // This example has the following output: // Ellen Adams // Number of dynamic properties: 2

浙公网安备 33010602011771号