开发者

Can I use a the value of a variable as the name of property in c#?

开发者 https://www.devze.com 2022-12-14 11:35 出处:网络
How do all! I want to be able to access a value in a class using the variable passed to a procedure. e.g. _results.project开发者_开发百科ion[2].Current.FundDC to become something like

How do all!

I want to be able to access a value in a class using the variable passed to a procedure.

e.g. _results.project开发者_开发百科ion[2].Current.FundDC to become something like

_results.projection[2].termId.varName

where termId can be Current, Future or Percent

and varName can be a large list :)

Any suggestions?

Answers on a postcard please :)


You can do this with reflection using Type.GetProperty to get a PropertyInfo and then PropertyInfo.GetValue to get the value.

Alternatively you could just switch on the name passed to you... both are somewhat icky, to be honest. Is the only way of receiving this information as a string? What's the bigger picture here?


Check out C# 4.0 (coming with VS2010), DynamicObject, and some more magic... read this blog post.

0

精彩评论

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