Expression.PropertyOrField(Expression, String) Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Создает объект MemberExpression , представляющий доступ к свойству или полю.
public:
static System::Linq::Expressions::MemberExpression ^ PropertyOrField(System::Linq::Expressions::Expression ^ expression, System::String ^ propertyOrFieldName);
public static System.Linq.Expressions.MemberExpression PropertyOrField(System.Linq.Expressions.Expression expression, string propertyOrFieldName);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Creating Expressions requires unreferenced code because the members being referenced by the Expression may be trimmed.")]
public static System.Linq.Expressions.MemberExpression PropertyOrField(System.Linq.Expressions.Expression expression, string propertyOrFieldName);
static member PropertyOrField : System.Linq.Expressions.Expression * string -> System.Linq.Expressions.MemberExpression
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Creating Expressions requires unreferenced code because the members being referenced by the Expression may be trimmed.")>]
static member PropertyOrField : System.Linq.Expressions.Expression * string -> System.Linq.Expressions.MemberExpression
Public Shared Function PropertyOrField (expression As Expression, propertyOrFieldName As String) As MemberExpression
Параметры
- expression
- Expression
Объект Expression , в котором Type содержится свойство или поле с именем propertyOrFieldName.
- propertyOrFieldName
- String
Имя свойства или поля для доступа.
Возвращаемое значение
ОбъектMemberExpression, равный свойствуexpression, Expression свойству NodeTypeMemberAccess, заданному, и Member свойству, заданному PropertyInfo для свойства или FieldInfo поля, которое обозначаетсяpropertyOrFieldName.
- Атрибуты
Исключения
expression или propertyOrFieldName есть null.
В ней не определено expressionсвойство или полеpropertyOrFieldName. Тип или базовые типы.
Примеры
В следующем примере показано, как создать выражение, представляющее доступ к свойству или полю.
// Add the following directive to your file:
// using System.Linq.Expressions;
class TestClass
{
public int sample { get; set; }
}
static void TestPropertyOrField()
{
TestClass obj = new TestClass();
obj.sample = 40;
// This expression represents accessing a property or field.
// For static properties or fields, the first parameter must be null.
Expression memberExpr = Expression.PropertyOrField(
Expression.Constant(obj),
"sample"
);
// The following statement first creates an expression tree,
// then compiles it, and then runs it.
Console.WriteLine(Expression.Lambda<Func<int>>(memberExpr).Compile()());
}
// This code example produces the following output:
//
// 40
' Add the following directive to your file:
' Imports System.Linq.Expressions
Class TestClass
Public Property Sample As Integer
End Class
Sub TestPropertyOrField()
Dim obj As New TestClass()
obj.Sample = 40
' This expression represents accessing a property or field.
' For static properties or fields, the first parameter must be Nothing.
Dim memberExpr As Expression = Expression.PropertyOrField(
Expression.Constant(obj),
"Sample"
)
' The following statement first creates an expression tree,
' then compiles it, and then runs it.
Console.WriteLine(Expression.Lambda(Of Func(Of Integer))(memberExpr).Compile()())
End Sub
' This code example produces the following output:
'
' 40
Комментарии
Свойство Type результирующего MemberExpression объекта равно PropertyType или FieldType свойствам PropertyInfo объекта или FieldInfoсоответственно, представляющего свойство или поле, обозначаемое propertyOrFieldName.
Этот метод выполняет поиск expression. Тип и его базовые типы для свойства экземпляра или поля с именем propertyOrFieldName. Статические свойства или поля не поддерживаются. Общедоступные свойства и поля задаются предпочтениями по сравнению с неиграционными свойствами и полями. Кроме того, свойства задаются предпочтениями по полям. Если найдено соответствующее свойство или поле, этот метод передает expression и FieldInfoPropertyInfo представляет это свойство или поле Property соответственноField.