private Field ( |
||
expression | ||
field | ||
return |
// Define the type of the field var field = typeof(MyClass).GetField("MyField"); // Create a parameter expression for the object instance var instance = Expression.Parameter(typeof(object), "instance"); // Convert the instance to the correct type var convertedInstance = Expression.Convert(instance, typeof(MyClass)); // Create the field access expression var fieldAccess = Expression.Field(convertedInstance, field); // Compile the expression and invoke it var getValue = Expression.Lambda>(fieldAccess, instance).Compile(); var result = getValue(null); // Returns the value of the static field
// Create a parameter expression for the object instance var instance = Expression.Parameter(typeof(MyClass), "instance"); // Create the field access expression var fieldAccess = Expression.Field(instance, "MyField"); // Compile the expression and invoke it var getValue = Expression.LambdaThese code snippets demonstrate how to use the Expression Field to access fields of objects dynamically at runtime. This class is part of the System.Linq.Expressions namespace in the .NET Framework, which is a library for building and executing dynamic queries in C#.>(fieldAccess, instance).Compile(); var obj = new MyClass(); var result = getValue(obj); // Returns the value of the instance field
private Field ( |
||
expression | ||
field | ||
return |