


The following editor will bring you a detailed explanation of C# dynamic objects (dynamic implementation of methods and properties). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let's follow the editor and take a look.
C#'s dynamic object properties are relatively simple to implement. If you want to implement dynamic methods like dynamic languages, it is more difficult, because dynamic objects, extension methods, and anonymous methods cannot Use direct methods. Here we still use objects and delegates to simulate the implementation of this dynamic method. It looks like a JavaScript object:
1) Define a delegate , the number of parameters is variable, and the parameters are all of object type: most of the delegates here have a dynamic parameter, which represents the dynamic object itself that calls this delegate.
public delegate object MyDelegate(dynamic Sender, params object[] PMs);
2) Define a delegated reproduction object, because dynamic objects cannot directly use anonymous methods, here we use objects to carry them:
public class DelegateObj { private MyDelegate _delegate; public MyDelegate CallMethod { get { return _delegate; } } private DelegateObj(MyDelegate D) { _delegate = D; } /// <summary> /// 构造委托对象,让它看起来有点javascript定义的味道. /// </summary> /// <param name="D"></param> /// <returns></returns> public static DelegateObj Function(MyDelegate D) { return new DelegateObj(D); } }
3) Define a dynamic object:
public class DynObj : DynamicObject { //保存对象动态定义的属性值 private Dictionary<string, object> _values; public DynObj() { _values = new Dictionary<string, object>(); } /// <summary> /// 获取属性值 /// </summary> /// <param name="propertyName"></param> /// <returns></returns> public object GetPropertyValue(string propertyName) { if (_values.ContainsKey(propertyName) == true) { return _values[propertyName]; } return null; } /// <summary> /// 设置属性值 /// </summary> /// <param name="propertyName"></param> /// <param name="value"></param> public void SetPropertyValue(string propertyName,object value) { if (_values.ContainsKey(propertyName) == true) { _values[propertyName] = value; } else { _values.Add(propertyName, value); } } /// <summary> /// 实现动态对象属性成员访问的方法,得到返回指定属性的值 /// </summary> /// <param name="binder"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { result = GetPropertyValue(binder.Name); return result == null ? false : true; } /// <summary> /// 实现动态对象属性值设置的方法。 /// </summary> /// <param name="binder"></param> /// <param name="value"></param> /// <returns></returns> public override bool TrySetMember(SetMemberBinder binder, object value) { SetPropertyValue(binder.Name, value); return true; } /// <summary> /// 动态对象动态方法调用时执行的实际代码 /// </summary> /// <param name="binder"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { var theDelegateObj = GetPropertyValue(binder.Name) as DelegateObj; if (theDelegateObj == null || theDelegateObj.CallMethod == null) { result = null; return false; } result = theDelegateObj.CallMethod(this,args); return true; } public override bool TryInvoke(InvokeBinder binder, object[] args, out object result) { return base.TryInvoke(binder, args, out result); } }
Application test code:
dynamic theObj = new DynObj(); theObj.aaa = "this is a test";//动态属性 //动态方法,这里不能没法定义参数,调用的时候可以是任意多参数,具体参数类型和含义就只能自己去小心处理了. theObj.show = DelegateObj.Function((s, pms) => { if (pms != null && pms.Length > 0) { MessageBox.Show(pms[0].ToString() + ":" + s.aaa); } else { MessageBox.Show(s.aaa); } return null; } ); theObj.show("hello");
Although it looks It sounds a bit like JS defining object methods, but since C# is a static language, the dynamic simulation mechanism provided is still limited. It seems to be dynamic, but all value storage and methods need to be processed by writing your own code.
The above code is tested OK on vs2010, windows 2008 server, and framework 4.0.
The above is the detailed content of Detailed explanation of C# dynamic object dynamic implementation methods and attribute dynamic code. For more information, please follow other related articles on the PHP Chinese website!

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
