我做下一件事......我将一些控件的字段传递给一些函数,例如:
class ScenarioSelector
{
public ScenarioSelector()
{
SubjectInfo.SetStr(lbl_labs_header.Text);
}
}
class SubjectInfo
{
public static void SetStr(object obj)
{
string name = obj.GetType().Name;
string full_name = obj.GetType().FullName;
Type t = obj.GetType();
//FieldInfo fi = FieldInfo.GetFieldFromHandle(/*I don't have any handle here*/);
//Somehow understand that passed object is... "ScenarioSelector.lbl_labs_header.Text" and set it's value depending from it.
}
}
函数 SetStr 应该理解传递对象的字段名称,并根据它的名称设置它的值。我尝试了一些东西,但无法得到我需要的东西,我只得到 System.String 作为名称。
这背后的整个想法是界面翻译。我想在文件中存储类似: [ScenarioSelector.lbl_labs_header.Text][TEXT_ON_THIS_LABEL] 并通过调用函数SetStr轻松设置它
也许您对如何以另一种方式或修复我的方式有一些想法?
PS基于Medinoc示例,我这样做了:
static void Test3<T>(Expression<Func<T>> exp)
{
Expression body = exp.Body;
List<string> memberNames = new List<string>();
MemberInfo previousMember = null;
while(body.NodeType == ExpressionType.MemberAccess)
{
MemberExpression memberBody = (MemberExpression)body;
string memberName = memberBody.Member.Name;
if (previousMember == null) //this is first one
{
switch (memberBody.Member.MemberType)
{
case MemberTypes.Field:
((FieldInfo)memberBody.Member).SetValue(/*How to get the object instance?*/, "some_val");
break;
case MemberTypes.Property:
break;
default:
break;
}
}
if (memberBody.Expression.NodeType == ExpressionType.Constant && previousMember != null) //If it's the 'last' member, replace with type
memberName = previousMember.DeclaringType.Name;
memberNames.Add(memberName);
previousMember = memberBody.Member;
body = memberBody.Expression;
}
memberNames.Reverse();
Console.WriteLine("Member: {0}", string.Join(".", memberNames));
}
但仍然不知道如何获取对象实例来设置所需的值。