2012-10-11 16 views

回答

3

一個乾淨的方式做到這一點是通過在剃刀文件使用本地函數

@functions 
{ 
    private Test GetTestAttribute(object obj) 
    { 
     // TODO: This returns null if TestAttribute was not on the class 
     TestAttribute myAttribute = 
      Attribute.GetCustomAttribute(obj, typeof (TestAttribute)) as TestAttribute; 
    } 
} 

<li>@GetTestAttribute(myClassInstance)</li> 

參考: http://msdn.microsoft.com/en-us/library/71s1zwct.aspx

如果您需要在屬性名稱通過檢查,您可以使用

Type.GetType(string typeName) 

取決於你在做什麼,你也可以改變GetTestAttribute到一個通用的功能與像

private T GetAttribute<T>(object obj) 
簽名