可以这样做吗?
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))
请确定期望的值是什么,但这会给您匹配属性的值。
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));
你的样品看起来很奇怪。每个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"]);
我建议在这种情况下使用enum,使用枚举可以做很多事情,我举一个例子:
枚举定义:
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.
}
可以实例化,可以比较,可以强制转换。
那么为什么不使用枚举呢?当你有一辆车时,你不必跑。