开发者

Default attribute list should come to my class definition in c# .net

开发者 https://www.devze.com 2023-02-04 09:10 出处:网络
I have a employee class: public class Employee { public string Name { get; set; } public Int32 Salary { get; set; }

I have a employee class:

public class Employee
{

        public string Name { get; set; }
        public Int32 Salary { get; set; }
        public DateTime DateOfBirth { get; set; }
}

and I have created a custom Attribute CustomeAttribute as

public class CustomAttributes : Attribute
{

        public  int Sequence {set;get;}
        public  int Length { set; get; }

}

I am using CustomAttribute as attribute in Employee as

public class Employee
{

    public string Name { get; set; }
    public Int32 Salary { get; set; }
    public DateTime DateOfBirth { get; set; }
} 

public class Employee
{

    [CustomAttributes(Sequence=1,Length=10)]
    public string Name { get; set; }
    [CustomAttributes(Sequence = 2, Length= 6)]
    public Int32 Salary { get; set; }
    [CustomAttributes(Sequence =3, Length = 8)]
    public DateTime DateOfBirth { get; set; }
}

I want to validate attribute collection should be there for each property definition. If I add new property Age to ´Employee` as

public class Employee 
{
    [CustomAttributes(Sequence=1,Length=10)]
    public string Name { get; set; }
    [CustomAttributes(Sequence = 2, Length= 6)]
    public Int32 Salary { get; set; }
    [CustomAttributes(Sequence =3, Length = 8)]
    public DateTime DateOfBirth { get; set; }

    public int Age {get;set;}
}

I 开发者_开发技巧should get compile time error as attributes are missing. Which will ensure writing Attribute values to each of property of a that class as well to a class which is from same assembly.??

I should get compile time error for a property without attribute values.


There is no way of generating a compile-time error for this. However, you could do something with reflection, in either your unit tests or the #debug build - simply iterate over the properties, checking Attribute.IsDefined(property, typeof(CustomAttributes))

0

精彩评论

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

关注公众号