-2

我有一个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;
   }
}

我想要2。我尝试valueid以下代码,但它不起作用。

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

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

帮帮我,我不知道它有什么问题。我对MVC没有深入的了解。

4

3 回答 3

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
}
于 2013-05-30T10:37:33.850 回答
1
Byte Payment_Type_Id = 2; // <- int will be better here
String val = Payment_Type.PaymentTypeList()[Payment_Type_Id].value.ToString();
于 2013-05-30T10:47:32.577 回答
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 将始终在列表中。如果不是,您将需要进行一些检查以避免异常。

于 2013-05-30T10:49:11.600 回答