强大的.NET中键入属性名称属性、强大、名称、NET

由网友(吟唱゛一世浮华)分享简介:说我有一类具有一个属性Say I have a class with one propertyPublic Class MyClassPublic Property MyItem() as Object....End PropertyEnd Class我要的属性的名称传递给函数调用。 (请不要问为什么它应该做这样...

说我有一类具有一个属性

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)

推荐答案

下面是使用类从System.Linq.Ex$p$pssions.

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
阅读全文

相关推荐

最新文章