如何通过Lambda表达式传递属性? [英] How can I pass a property in via a lambda expression?

查看:89
本文介绍了如何通过Lambda表达式传递属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有一些单元测试,我们希望能够设置一些具有私有设置器的属性.目前,我正在通过反射和此扩展方法进行操作:

There are some unit tests on my project where we want to be able to set some properties that have private setters. Currently I'm doing it via reflection and this extension method:

public static void SetPrivateProperty(this object sourceObject, string propertyName, object propertyValue)
{
    sourceObject.GetType().GetProperty(propertyName).SetValue(sourceObject, propertyValue, null);
}

假设我有一个这样的TestObject:

Assuming I had a TestObject like this:

public class TestObject
{
    public int TestProperty{ get; private set; }
}

然后我可以在单元测试中称其为:

I can then call this in my unit tests as follows:

myTestObject.SetPrivateProperty("TestProperty", 1);

但是,我希望在编译时验证属性名称,因此,我希望能够通过表达式将属性传递,如下所示:

However, I'd like to have validation of the property name at compile time, and thus I'd like to be able to pass the property in via expression, like this:

myTestObject.SetPrivateProperty(o => o.TestProperty, 1);

我该怎么做?

推荐答案

C#6.0的新功能:

New to C# 6.0 : nameof(property)

这篇关于如何通过Lambda表达式传递属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆