问题描述
有已经有很多愿望,包括nameof()运算符在C#中,这样就可以做,例如,nameof(Customer.Name),这将返回名。
There's been a lot of wishes to include nameof () operator in C#, so that you could do, for instance, nameof (Customer.Name), which will return you "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 typesafe.
我记得,有针对.NET 3.5的替代方法涉及拉姆达前pressions,这样你可以得到失踪nameof操作符的效果,但现在我找不到它。任何人都可以提醒我?
而且......对于.NET 2.0 ...有什么该死的办法做到这一点?
谢谢!
I remember, there was a workaround for .NET 3.5 which involved lambda expressions, so that you could get the effect of missing "nameof" operator, but I could not find it now. Anyone can remind me?And...for .NET 2.0...is there any damn way to do it?Thanks!
推荐答案
这code基本上没有了:
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 code ...)
(Of course it is 3.5 code...)
这篇关于对于nameof解决方法()运算符在C#中:类型安全的数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!