0

这是否可以执行以下操作:

public class Months
{
    public double Jan {get;set;}
    public double Feb {get;set;}
    public double Mar {get;set;}
}

进而

List<Months> myList = new List<Months>();
string monthName = "Jan";

有可能是这样的吗?

myList.where(x=>x.PropertyName.Equals(monthName))
4

3 回答 3

3

请注意确定什么是预期值,但这会给您匹配属性的值。

List<Months> myList = new List<Months>();
myList.Add(new Months(){ Jan = 2.2});
string monthName = "Jan";
var result = myList.Select(x => x.GetType().GetProperty(monthName).GetValue(x, null));
于 2013-01-14T09:41:41.480 回答
2

你的样本看起来很奇怪。每个Month类都有Jan属性。

更新:

public class Months
{
    private readonly IDictionary<string, double> _backfiends;

    public double Jan
    {
        get { return _backfiends["Jan"]; }
        set { _backfiends["Jan"] = value; }
    }

    public IDictionary<string, double> Backfields
    {
        get { return _backfiends; }   
    }

    public Months()
    {
        _backfiends = new Dictionary<string, double>();
        _backfiends["Jan"] = 0;
    }
}

用法:

var myList = new List<Months>();
myList.Add(new Months(){Jan = 123});
var withJan = myList.Select(x => x.Backfields["Jan"]);
于 2013-01-14T09:38:03.243 回答
1

我建议在这种情况下使用枚举,你可以用枚举做很多事情,我举一个例子:

枚举定义:

public enum Month 
{ Jan=1, Feb, Mar, Apr, may, Jun, Jul, Aug, Sep, Oct, Nov, Dec }

在按钮点击:

Month current = Month.Jan; //staticly checking a month

if(current == Month.Jan)
    MessageBox.Show("It's Jan");
else
    MessageBox.Show("It's not Jan.");

List<Month> specialMonthes = new List<Month>();
specialMonthes.Add(Month.Oct);
specialMonthes.Add(Month.Apr);
specialMonthes.Add(Month.Jan);
//Search the list for the month we are in now
foreach (Month specialMonth in specialMonthes)
{
    if ((int)specialMonth == DateTime.Now.Month) //dynamically checking this month
        MessageBox.Show(string.Format("It's {0} now & {0} is a special month.",  
            specialMonth));
        //Output: It's Jan now and Jan is a special month.
}

你可以化解,你可以比较,你可以施放。
那么为什么不使用枚举呢?有了车就不用跑了。

于 2013-01-14T09:51:31.707 回答