0

我有以下模型:

Public Class MyModel

    Public Property MyModelId As Integer
    Public Property Description As String
    Public Property AnotherProperty As String

End Class

有没有一种方法可以将模型的属性名称作为字符串表示形式获取,如下面的代码?

Dim propertyName as String = GetPropertyNameAsStringMethod(MyModel.Description)

所以 propertyName 变量的值是“描述”。

4

5 回答 5

2

检查此 SO 线程上的 Darin Dimitrov 的答案- Reflection - get property name

class Foo
{
    public string Bar { get; set; }
}

class Program
{
    static void Main()
    {
        var result = Get<Foo, string>(x => x.Bar);
        Console.WriteLine(result);
    }

    static string Get<T, TResult>(Expression<Func<T, TResult>> expression)
    {
        var me = expression.Body as MemberExpression;
        if (me != null)
        {
            return me.Member.Name;
        }
        return null;
    }
}

希望这有帮助..

于 2013-01-04T14:52:19.793 回答
1

这是一个可用于任何属性的辅助扩展方法:

public static class ReflectionExtensions
{
    public static string PropertyName<T>(this T owner, 
        Expression<Func<T, object>> expression) where T : class
    {
        if (owner == null) throw new ArgumentNullException("owner");
        var memberExpression = (MemberExpression)expression.Body;
        return memberExpression.Member.Name;
    }

}

但是,这仅适用于类的实例。您可以编写一个类似的扩展方法,直接对类型进行操作。

于 2013-01-04T14:51:25.667 回答
1

你需要使用反射来做到这一点。

已经有很多关于堆栈溢出的帖子,如下所示:

如何通过反射获取当前属性名称?

反射 - 获取属性名称

使用反射获取属性的字符串名称

反射 - 获取属性名称

我相信答案会是这样的:

 string prop = "name"; 
 PropertyInfo pi = myObject.GetType().GetProperty(prop);
于 2013-01-04T14:53:00.340 回答
0

创建一个扩展方法,然后在需要的地方使用它。

Private Shared Function GetPropertyName(Of T)(exp As Expression(Of Func(Of T))) As String
    Return (DirectCast(exp.Body, MemberExpression).Member).Name
End Function

看看这篇文章。

于 2013-01-04T14:54:42.977 回答
0

我已经解决了这个问题,编辑了一点@NiranjanKala 的源示例,

像这样转换vb.Net中的代码

<System.Runtime.CompilerServices.Extension()> _
Public Function GetPropertyName(Of T, TResult)(expression As Expression(Of Func(Of T, TResult))) As String
    Dim [me] = TryCast(expression.Body, MemberExpression)
    If [me] IsNot Nothing Then
        Return [me].Member.Name
    End If
    Return Nothing
End Function

然后我可以像这样调用分机

Dim propertyName as String = GetPropertyName(Of MyModel, String)(Function(x) x.Description)

然后 propertyName 变量将“描述”作为字符串值。

于 2013-01-04T15:15:46.637 回答