获取类的第n个属性 [英] Getting nth property of a class

查看:59
本文介绍了获取类的第n个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是C#语言的初学者

我有一个类似

public  class Plan
{
       int a;
       int b;
       int c;     
}  

可以以任何方式获取类的第n个属性.

Can in any way I get the nth property of the class.

例如: planObject.propertyIndex

这将对我的项目有很大帮助,因为我将获得表示要更改其值的属性的索引号.我现在正在做的是if ... else.

This would be of great help for my project, as I am getting index number denoting the property whose value is to be changed. What I am doing right now is using if...else .

   if(index ==1)
   {
         planObject.a = 100;
   }
   else if(index ==2)    
   {
      planObject.b = 100;
   }

还有其他使用反射的解决方案吗?

Is there any other solution for this by using reflection?

推荐答案

警告一词,对于初学者来说根本不是.而且这可能只会使代码更复杂.这个答案是理所当然的,您对扩展方法和反射有一定的了解.

A word of WARNING, this is in no way for beginners at all. And it might just make the code more complex. This answer takes for granted that you have a working knowledge of extension methods and reflection.

public static class PlanExtension
{
  PropertyInfo _info = typeof(Plan).GetProperties();

  public static void SetValue(this Plan plan, int index, int value)
  {
    var prop = _info[index - 1]; // So 1 maps to 0.. or 1 in this case
    prop.SetValue(plan, value, null);
  }

  public static int GetValue(this Plan plan, int index)
  {
    var prop = _info[index - 1]; // Mapping magic
    return (int) prop.GetValue(plan, null);
  }
}

这样称呼:

var p = new Plan();
p.SetValue(1, 139); // "a"
var b = p.GetValue(2); // "b"

如果您对属性具有可定义的顺序(例如名称或其他名称),这将有所帮助.另外,在进行反射时必须进行错误处理.

It would help if you had a definable order to the properties, like name or something. Also, error handling is a must when it comes to reflection.

这篇关于获取类的第n个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆