开发者

how to get private field value by string inside an object without using switch?

say, classA has private field A,B,C,D,E.. I wanna build a private (i belive i cannot do public?) method StringToProperty inside the classA开发者_运维技巧 so that StringToProperty("A") returns A.


First, sure it can be a public method. If you expect that the method can't be public because it's calling stuff that is private, that is not accurate. Think of public methods/properties as controlled windows into the underlying private members.

So to retrieve the property, can use use reflection.

public string StringToProperty(string fieldName)
{
  Type myType = this.GetType();
  FieldInfo field = myType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
  return Convert.ToString(field.GetValue(this)); 
}

Look here for more info: http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.getvalue.aspx

That should do it, but I warn you that reflection may introduce a performance penalty, depending on what you are loading and how often. Please ensure that it is performing sufficient for your needs, because you may need to do some sort of caching of the FieldInfo data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜