如何在c#中获取类数组的值?

时间:2013-05-30 10:35:34

标签: c# asp.net-mvc asp.net-mvc-3

我的课程Payment_Type包含两个字段idvalue

public class Payment_Type
{
  public int id { get; set; }
  public string value { get; set; }
  public Payment_Type(int p, string p_2)
  {
    this.id = p;
    this.value = p_2;
  }
  public static Payment_Type[] PaymentTypeList()
  {
     Payment_Type[] pay = new Payment_Type[4];
     pay[0] = new Payment_Type(1, "Cheque");
     pay[1] = new Payment_Type(2, "Demand Draft");
     pay[2] = new Payment_Type(3, "Cash");
     pay[3] = new Payment_Type(4, "Other");
     return pay;
   }
}

我想要value id 2.我尝试使用代码,但它无效。

Byte Payment_Type_Id = 2
string val = Payment_Type.PaymentTypeList().GetValue(Payment_Type_Id).ToString();

它给我结果为 Payment_Type类的名称空间,即CRMEvent.Models.CRM.BLogic.Payment_Type

帮帮我,我不知道它有什么问题。我对MVC并不了解。

3 个答案:

答案 0 :(得分:1)

您可以使用LINQ:

int paymentTypeId = 2;
var paymentType = Payment_Type.PaymentTypeList().FirstOrDefault(x => x.id == paymentTypeId);
if (paymentType == null)
{
    // no value with id=2 was found in the array
}
else
{
    // you could use the paymentType.value here
}

答案 1 :(得分:1)

Byte Payment_Type_Id = 2; // <- int will be better here
String val = Payment_Type.PaymentTypeList()[Payment_Type_Id].value.ToString();

答案 2 :(得分:1)

您遇到的问题是Payment_Type.PaymentTypeList().GetValue(Payment_Type_Id)会返回Payment_Type类型的对象。当您在此上调用ToString方法时,它使用基本对象定义,该定义仅显示对象类型。

Payment_Type.PaymentTypeList().GetValue(Payment_Type_Id).Value

这将获得数组中所选项的字符串值。

您可能希望查看访问数组中项目的不同方法。我个人更喜欢使用字典(因为这种查找正是它的用途),这意味着如果你的项目由于某种原因在索引中有间隙,你就不会有查询问题。

public static Dictionary<int, Payment_Type> PaymentTypeList()
{
    var pay = new Dictionary<int, Payment_Type>();
    pay.Add(1, new Payment_Type(1, "Cheque"));
    pay.Add(2, new Payment_Type(2, "Demand Draft"));
    pay.Add(3, new Payment_Type(3, "Cash"));
    pay.Add(4, new Payment_Type(4, "Other"));
    return pay;
}

然后您可以使用以下方式访问您想要的内容:

Byte Payment_Type_Id = 3;
string val = Payment_Type.PaymentTypeList()[Payment_Type_Id].value;

这假定提供的id将始终在列表中。如果不是,您将需要进行一些检查以避免例外。