问题描述
在C#中包含一个 nameof
操作符已经有了很多的想法。作为这个操作符如何工作的例子, nameof(Customer.Name)
将返回字符串Name
。
There has been a lot of sentiment to include a nameof
operator in C#. As an example of how this operator would work, nameof(Customer.Name)
would return the string "Name"
.
我有一个域对象。我必须绑定它。而且我需要属性的名称作为字符串。我希望他们是类型安全的。
I have a domain object. And I have to bind it. And I need names of properties as strings then. And I want them to be type-safe.
我记得在.NET 3.5中遇到了一个解决方法,它提供了 nameof
并涉及lambda表达式。但是,我无法找到此解决方法。任何人都可以为我提供这种解决方法?
I remember coming across a workaround in .NET 3.5 which provided the functionality of nameof
and involved lambda expressions. However, I have not been able to locate this workaround. Can anyone provide that workaround to me?
我也有兴趣实现 nameof
的功能
推荐答案
这段代码基本上是这样的:
This code basically does that:
class Program
{
static void Main()
{
var propName = Nameof<SampleClass>.Property(e => e.Name);
Console.WriteLine(propName);
}
}
public class Nameof<T>
{
public static string Property<TProp>(Expression<Func<T, TProp>> expression)
{
var body = expression.Body as MemberExpression;
if(body == null)
throw new ArgumentException("'expression' should be a member expression");
return body.Member.Name;
}
}
(当然是3.5代码...)
(Of course it is 3.5 code...)
这篇关于C#中缺少“nameof”运算符以进行类型安全数据绑定的解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!