强大的.NET中键入属性名称 [英] Strong Typing a property name in .NET
问题描述
说我有一类具有一个属性
Say I have a class with one property
Public Class MyClass
Public Property MyItem() as Object
....
End Property
End Class
我要的属性的名称传递给函数调用。 (请不要问为什么它应该做这样一来,它是一个第三方的框架)。例如
I have to pass the name of the property to a function call. (Please don't ask why it should be done this way, its a third party framework). For example
SomeFunc("MyItem")
但我希望做的是,改变串入一个强类型的参数。意思是,如果属性名称重命名或更改,应该体现在这里了。
But what I would like to do is, change the string into a strongly typed parameter. Meaning, if the property name is renamed or changed, it should be reflected here too.
因此,一些这种类型的:
So something of this type :
Dim objectForStrongTyping as New MyClass()
SomeFunc(objectForStrongTyping.MyItem().Name())
我相信这是行不通的。有没有办法这个强类型可以做什么? (C#或VB.NET,任何事情是凉)
I am sure this won't work. Is there a way this strong typing can be done? (C# or VB.NET, any thing is cool)
推荐答案
下面是使用类从<一个一个的解决方案href="http://msdn.microsoft.com/en-us/library/system.linq.ex$p$pssions.aspx"><$c$c>System.Linq.Ex$p$pssions$c$c>.
Here is a solution using classes from System.Linq.Expressions
.
static MemberInfo GetMemberInfo<TObject, TProperty>(
Expression<Func<TObject, TProperty>> expression
) {
var member = expression.Body as MemberExpression;
if (member != null) {
return member.Member;
}
throw new ArgumentException("expression");
}
刚刚抛出此一类的地方(防爆pressionHelper
?)。
用法:
class SomeClass {
public string SomeProperty { get; set; }
}
MemberInfo member = GetMemberInfo((SomeClass s) => s.SomeProperty);
Console.WriteLine(member.Name); // prints "SomeProperty" on the console
这篇关于强大的.NET中键入属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!