Expression<Func<T>> 是否适用于混合的静态/实例成员?
Does Expression<Func<T>> work with mixed static / instance members?
我正在使用 GetMemberName<T>(Expression<Func<T>> member)
检索成员名称。当 Foo
属性 不使用 static
修饰符时,该成员不能与此方法一起使用:
An object reference is required for the non-static field, method, or
property 'Program.Foo'
由于我对LINQ Expressions的理解程度不是很深,所以想请教:
问题: 除了 nameof(Foo)
之外,还有其他方法可以访问 "equivalent" 中的成员吗方法?目标是获取 属性 元数据,例如名称,而不是从实例访问其值。
public class Program
{
public /*static*/ int Foo { get; set; }
public static void Main(string[] args)
{
Console.WriteLine(GetMemberName(() => Foo));
}
public static string GetMemberName<T>(Expression<Func<T>> member)
{
return (member.Body as MemberExpression)?.Member.Name;
}
}
您将代码放在 public
staticvoid Main(string[] args)
中,这意味着您没有 Program
实例以访问 Foo
实例成员 。它与表达式无关,GetMemberName
无论如何都会按照你写的那样工作。
我正在使用 GetMemberName<T>(Expression<Func<T>> member)
检索成员名称。当 Foo
属性 不使用 static
修饰符时,该成员不能与此方法一起使用:
An object reference is required for the non-static field, method, or property 'Program.Foo'
由于我对LINQ Expressions的理解程度不是很深,所以想请教:
问题: 除了 nameof(Foo)
之外,还有其他方法可以访问 "equivalent" 中的成员吗方法?目标是获取 属性 元数据,例如名称,而不是从实例访问其值。
public class Program
{
public /*static*/ int Foo { get; set; }
public static void Main(string[] args)
{
Console.WriteLine(GetMemberName(() => Foo));
}
public static string GetMemberName<T>(Expression<Func<T>> member)
{
return (member.Body as MemberExpression)?.Member.Name;
}
}
您将代码放在 public
staticvoid Main(string[] args)
中,这意味着您没有 Program
实例以访问 Foo
实例成员 。它与表达式无关,GetMemberName
无论如何都会按照你写的那样工作。