简体   繁体   English

我可以在C#中使用变量的值作为属性的名称吗?

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

How do all! 怎么办!

I want to be able to access a value in a class using the variable passed to a procedure. 我希望能够使用传递给过程的变量访问类中的值。

eg _results.projection[2].Current.FundDC to become something like 例如_results.projection [2] .Current.FundDC变成类似

_results.projection[2].termId.varName _results.projection [2] .termId.varName

where termId can be Current, Future or Percent 其中termId可以是Current,Future或Percent

and varName can be a large list :) 和varName可以是一个很大的列表:)

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. 您可以使用Type.GetProperty来获取PropertyInfo ,然后使用PropertyInfo.GetValue来获取反射值。

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? 这里的大局是什么?

查看C#4.0(随VS2010一起提供),DynamicObject和其他一些魔术... 阅读此博客文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM