是否可以将两个C#属性合并成一个? [英] Is it possible to merge two C# attributes into one?

查看:155
本文介绍了是否可以将两个C#属性合并成一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我公司的一个项目中首先使用EF6代码。在该项目中,POCO类中有几个属性存储波斯日期信息
(例如1394/01/24)。在我们的数据库中,这些值存储在CHAR(10)列中。



我使用字符串属性将这些值存储在我的POCO中,并且必须附加ColumnAttribute和每个日期属性的StringLengthAttribute:

  public class MyPoco 
{
...

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

...
}

好奇地知道如果我有一种方法可以创建一个结合这两个属性的行为的自定义属性,以便我可以这样做:

  public class MyPoco 
{
...

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

...
}

其中 DateColumnAttribute应用这两个属性做什么。

解决方案

正如Florian所说:这不是如何工作



属性到底是一个派生自基类Attribute的类。你想要做的是创建一个新的属性(类),它将属性Column和StringLength相结合。



这是不可能的,因为我们将不得不创建一个新的属性,它从两个属性一起派生,但这是不可能的,因为.NET不允许多重继承。



这也是一个代码风格的问题。如果你可以做你想要的,你会隐藏原来的意图行为给开发者。他必须打开新的属性,意识到,它是两个人的组合。一切模糊代码的东西通常被认为是不良行为(除了增强可读性)


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.

解决方案

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)

这篇关于是否可以将两个C#属性合并成一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆