通过索引访问属性
我需要通过索引或类似的东西访问属性。 这个已经回答的问题中解释了原因。该答案使用 Linq,我更喜欢没有这种依赖性的东西。我无法控制班级。
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"];
}
}
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"];
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您无法控制该类,因此您可以使用扩展方法和反射来按名称获取属性值:
用法:
As you have no control over the class you can use extension method and reflection to get property value by name:
Usage:
use (编辑 - 根据评论):
它为您提供实例
c
名为S
的(公共)属性的值,无论c 的类型如何
并且根本不使用 LINQ,尽管我必须承认我不明白为什么 LINQ 会成为一个问题......use (EDIT - as per comment):
It gives you the value of the (public) property named
S
of the the instancec
regardless of the type ofc
and doesn't use LINQ at all although I must admit that I don't see why LINQ should be a problem...您可以通过在类和集合上使用默认属性来实现相同的目的。如果您始终需要字符串,则可以使用 Dictionary 类作为默认属性。
然后在构造函数中,您可以初始化
myDictionary["s"] = "some string";
然后您可以将 myClass 用作集合,因此 myClass["s"] 将返回“some string”。
反射通常表明您尚未创建 API 来完成您需要的工作,如果您有代码需要修改,那么我建议您使用默认属性。
请参阅此 MSDN 文章:
You can achieve the same thing by using a default property on your class and a collection. Provided that you will always want strings, you could use the Dictionary class as your default property.
Then in the constructor you could intialize
myDictionary["s"] = "some string";
You could then use the myClass as a collection, so myClass["s"] would return "some string".
Reflection is usually an indicator that you haven't created an API to do the job you need, if you have the code to modify then I recommend you use the default property.
See this MSDN article: