Is it possible to merge two C# attributes into one?

最后都变了- 提交于 2019-12-10 16:25:48

问题


I'm using EF6 code first in one of my company's projects. In the project there are a couple of properties in POCO classes that store Persian date information (for example 1394/01/24). In our database these values are stored in "CHAR(10)" columns.

I use string properties to store these values in my POCOs and have to attach "ColumnAttribute" and "StringLengthAttribute" to every date property:

public class MyPoco
{
    ...

    [Column(TypeName="CHAR")]
    [StringLength(10, MinimumLength=10)]
    public string MyDate {get; set;}

    ...
}

I'm curious to know if I there is a way to create a custom attribute that combines behaviours of those two attributes so that I could do something like this:

public class MyPoco
{
    ...

    [DateColumn]
    public string MyDate {get; set;}

    ...
}

where "DateColumnAttribute" applies what those two attributes do. It can definitely reduce typing.


回答1:


As Florian stated: that's no how it works

An Attribute is in the end a class which derives from a base class Attribute. What you are trying to do, is to create a new attribute (class), which combines the properties of both attributes Column and StringLength.

This is not possible, because we would have to create a new attribute, which derives from both attributes together, but that's not possible, since .NET does not allow multiple inheritance.

Also it's a question of code style. If you could do what you want, you would hide the original intended behavior to the developer. He would have to open the new attribute and realize, it's a combination of two others. Everything that obfuscates the code is commonly regarded bad behavior (except it enhances readability of course)



来源:https://stackoverflow.com/questions/29620891/is-it-possible-to-merge-two-c-sharp-attributes-into-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!