开发者

C# attribute: how to know class name which has field marked with attribute

开发者 https://www.devze.com 2023-01-12 20:16 出处:网络
particularly when overriding Asp.net MVC ValidationAttribute, is it possible to know class name which has field marked with attribute ? (AttributeUsage is AttributeTargets.Property)

particularly when overriding Asp.net MVC ValidationAttribute, is it possible to know class name which has field marked with attribute ? (AttributeUsage is AttributeTargets.Property)

public class UniqueAttribute: ValidationAttribute

        public override bool IsValid(object value)
        {
            // how to know which class has this attribute?开发者_如何学Go
        }


Given an instance of an attribute it is not possible to determine what class, field, method, etc ... originated this attribute. Primarily because it doesn't need to be attached to one. All attributes can be created just like a normal object and hence not be attached to anything

var instance = new UniqueAttribute();

You may need to use a different constructor but one must exist or it couldn't be applied to a member in the first place.

It is possible to go the other way though. Given a member or type to find out if it has a given attribute applied to it. For example, assuming there is a single instance of UnqiueAttribute attached to the type SomeType this code will retrieve it.

var type = typeof(SomeType);
var attrib = (UniqueAtrtibute)type.GetCustomAttributes(typeof(UnqiueAttribute),true)[0];


http://oreilly.com/catalog/progcsharp/chapter/ch18.html

0

精彩评论

暂无评论...
验证码 换一张
取 消