[英]Get member to which attribute was applied from inside attribute constructor?
我有一個自定義屬性,在我的自定義屬性的構造函數中,我想將我的屬性的屬性值設置為應用我的屬性的屬性的類型,是否有某種方式可以訪問應用該屬性的成員從我的屬性類里面?
恐怕屬性不能那樣工作。 它們只是“標記”,依附在對象上,但無法與它們交互。
屬性本身通常應該沒有行為,只包含它們所附加的類型的元數據。 與屬性相關的任何行為都應該由另一個類提供,該類查找屬性的存在並執行任務。
如果您對應用該屬性的類型感興趣,那么在您反映以獲取該屬性的同時,該信息將可用。
可以從.NET 4.5使用CallerMemberName
:
[SomethingCustom]
public string MyProperty { get; set; }
那么你的屬性:
[AttributeUsage(AttributeTargets.Property)]
public class SomethingCustomAttribute : Attribute
{
public StartupArgumentAttribute([CallerMemberName] string propName = null)
{
// propName == "MyProperty"
}
}
你可以做下一步。 這是一個簡單的例子。
//target class
public class SomeClass{
[CustomRequired(ErrorMessage = "{0} is required", ProperytName = "DisplayName")]
public string Link { get; set; }
public string DisplayName { get; set; }
}
//custom attribute
public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
{
public string ProperytName { get; set; }
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var propertyValue = "Value";
var parentMetaData = ModelMetadataProviders.Current
.GetMetadataForProperties(context.Controller.ViewData.Model, context.Controller.ViewData.Model.GetType());
var property = parentMetaData.FirstOrDefault(p => p.PropertyName == ProperytName);
if (property != null)
propertyValue = property.Model.ToString();
yield return new ModelClientValidationRule
{
ErrorMessage = string.Format(ErrorMessage, propertyValue),
ValidationType = "required"
};
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.