在 C# 中缺少用于类型安全数据绑定的“nameof"运算符的解决方法? [英] Workaround for lack of 'nameof' operator in C# for type-safe databinding?
问题描述
很多人都认为在 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?
如果可能的话,我也对在 .NET 2.0 中实现 nameof
功能的方法感兴趣.
I am also interested in a way to implement the functionality of nameof
in .NET 2.0 if that is possible.
推荐答案
这段代码基本上做到了:
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"运算符的解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!