簡體   English   中英

如何在MVC3中獲取模型的屬性名稱的字符串表示形式?

[英]How to get a string representation of a property name of a Model in MVC3?

我有以下模型:

Public Class MyModel

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

End Class

是否有一種方法可以獲取Model的屬性名稱作為字符串表示形式,例如以下代碼?

Dim propertyName as String = GetPropertyNameAsStringMethod(MyModel.Description)

因此,propertyName變量具有“ Description”作為值。

在此SO線程上檢查Darin Dimitrov的答案 -Reflection-get屬性名

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;
    }
}

希望有幫助。

這是可以用於任何屬性的輔助擴展方法:

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;
    }

}

但是,這僅適用於類的實例。 您可以編寫類似的擴展方法,該方法將直接對類型進行操作。

您需要使用反射來完成。

像這樣的堆棧溢出已經有大量的帖子:

如何通過反射獲取當前屬性名稱?

反射-獲取屬性名稱

使用反射獲取屬性的字符串名稱

反射-獲取屬性名稱

我相信答案將是:

 string prop = "name"; 
 PropertyInfo pi = myObject.GetType().GetProperty(prop);

創建一個擴展方法,然后在需要的地方使用它。

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

也看看這個帖子。

我通過編輯@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變量將“ Description”作為字符串值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM