如何创建一个具有熟悉功能的方法作为新的"?。"运营商?

时间:2016-01-06 16:42:18

标签: c# reflection lambda

使用C#6,我们可以使用新的?来访问属性和方法,而无需检查每个属性和方法是否为null。是否可以使用表达式编写具有siliar功能的方法?

例如,我必须使用一个奇怪的对象结构(来自第三方库,我们无法改变)。访问某些属性通常需要长链点:

rootObject.Services.First().Segments.First().AnotherCollection.First().Weight;

rootObject之后的任何对象都可以是null。我宁愿不在它周围加try/catch。另外,分别检查每个房产是很多工作。所以我想知道我是否可以将它传递给带有表达式的方法并遍历每个属性并检查其值:

var value = PropertyHelper.GetValue(() => rootObject.Services.First().Segments.First().AnotherCollection.First().Weight);

我猜它的签名就像:

public static T GetValue<T>(Expression<Func<T>> expression)
{
    // analyze the expression and evaluate each property/method
    // stop when null or return the value
}

我不确定表达是否符合我要做的事情,在开始试验之前,我想问一下它是否可能。

1 个答案:

答案 0 :(得分:2)

    public MainWindow()
    {   
        InitializeComponent();
        Combobox.DisplayMemberPath = "Text";
        Combobox.SelectedValuePath = "Value";
        Combobox.Items.Add(new { Text = "String", Value = 0 });
        Combobox.Items.Add(new { Text = "String", Value = 1 });
    }
        string[] array = new string[30];
        bool gotResponse = false;
    }
    private void StartButton_Click(object sender, RoutedEventArgs e)
    {
        Thread thread = new Thread(new ThreadStart(DoWork));
        thread.Start();
    }
    private void Next_click(object sender, RoutedEventArgs e)
    {
        gotResponse = true;
    }
    void DoWork()
    {
        for (int Step = 0; Step < 30; Step++)
        {
            while (!gotResponse)
            {

            }

            array[Step] = Combobox.SelectedValue.ToString();
            bool gotResponse = false;
        }
    }