按索引访问属性 [英] Access property by Index
本文介绍了按索引访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要通过索引或类似的东西来访问一个属性.这个已经回答的问题中解释了原因.该答案使用 Linq,我更喜欢没有这种依赖性的东西.我无法控制课程.
I need to access a property by an index or something similar. The reason why is explained in this already answered question. That answer uses Linq and I prefer something without that dependency. I have no control over the class.
public class myClass
{
private string s = "some string";
public string S
{
get { return s; }
}
}
class Program
{
static void Main(string[] args)
{
myClass c = new myClass();
// I would like something similar
// or same functionality
string s = c["S"];
}
}
推荐答案
使用(编辑 - 根据评论):
use (EDIT - as per comment):
string s = c.GetType().GetProperty ("S").GetGetMethod().Invoke (c, null).ToString();
它为您提供实例 c
的名为 S
的(公共)属性的值,而不管 c
的类型如何,并且不会根本不使用 LINQ,尽管我必须承认我不明白为什么 LINQ 应该是一个问题...
It gives you the value of the (public) property named S
of the the instance c
regardless of the type of c
and doesn't use LINQ at all although I must admit that I don't see why LINQ should be a problem...
这篇关于按索引访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文