如何从值中获取字段的 FieldInfo [英] How to get the FieldInfo of a field from the value
问题描述
我想访问 FieldInfo,用于字段上的 CustomAttributes 和其他目的,但我不想使用字符串来访问该字段,也不想遍历类中的所有字段.
I want to access the FieldInfo, for the CustomAttributes that are on a field, and other purposes, but I'd prefer not to use a string to access that field, nor to have to run through all the fields in a class.
如果我只是有,
class MyClass
{
#pragma warning disable 0414, 0612, 0618, 0649
private int myInt;
#pragma warning restore 0414, 0612, 0618, 0649
public MyClass()
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
Console.WriteLine( GetType().GetField("myInt", flags) );
foreach( FieldInfo fi in GetType().GetFields(flags) )
{
Console.WriteLine( string.Format("{0} {1} {2}", fi.Name, myInt, fi.GetValue(this) ) );
}
}
}
我知道我可以通过GetField"函数直接访问myInt"的FieldInfo,如果我有它的名字的字符串,或者循环通过GetFields",那将再次依赖于字符串myInt"确保您拥有正确的字段.
I know I can access the FieldInfo of "myInt" directly via the "GetField" function, if I have the string of it's name, or cycling through "GetFields", that would again rely upon having the string "myInt" to ensure you've the right field.
是否有任何可用的魔法,例如 ref myInt
或 out myInt
,或者一些我不知道的关键字,它们可以让我访问,还是我仅限于需要字符串名称来获取它?
Is there any sort of magic that's available like ref myInt
, or out myInt
, or some keyword that I don't know about yet which would give me access, or am I limited to needing the string name to get it?
推荐答案
你的意思是从编译的表达式而不是字符串中获取成员信息?例如
Do you mean getting the memberinfo from a compiled expression rather than the string? e.g
class Program
{
public static void Main()
{
var cls = new MyClass();
Console.WriteLine(GetMemberInfo(cls, c => c.myInt));
Console.ReadLine();
}
private static MemberInfo GetMemberInfo<TModel, TItem>(TModel model, Expression<Func<TModel, TItem>> expr)
{
return ((MemberExpression)expr.Body).Member;
}
public class MyClass
{
public int myInt;
}
}
这篇关于如何从值中获取字段的 FieldInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!