[英]In MVC3 how do I get a DataContract-attributed object that was posted to my action?
[英]How do I get at the metadata of attributed parameters?
如何在以下代碼中獲得參數的屬性?
public void SomeMethod([SomeAttribute] string s)
{
var someAttribute = ?
}
而且我意識到該屬性通常不適合在使用該屬性的方法中使用……只是使示例保持簡單。
我只是想通了:
var someAttribute = typeof(SomeClass).GetMethod("SomeMethod").GetParameters().First().GetCustomAttributes(false);
我只是放屁了,正在使用Attributes屬性而不是GetCustomAttributes方法。
首先,您需要一個MethodInfo
:
var method = typeof(SomeType).GetMethod("SomeMethod");
然后,您可以檢查是否存在:
bool hasAttrib = Attribute.IsDefined(
method.GetParameters()[0], typeof(SomeAttribute));
或獲取一個實例(更昂貴):
var attrib = (SomeAttribute) Attribute.GetCustomAttribute(
method.GetParameters()[0], typeof(SomeAttribute));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.