0

これは、次のように sth を実行することは可能ですか:

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 に答える