2012-10-11 14 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) 
签名