在C#中的许多类中使用相同的属性束

时间:2015-08-05 13:56:32

标签: c# attributes

我试图在许多类中使用相同的属性。我怎样才能在C#中实现这个目标?

如果不清楚我想要实现的目标,请查看示例:

public class A
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
    public string Property3 { get; set; }

    [Attribute1]
    [Attribute2]
    [Attribute3]
    public string Foo { get; set; }
}

public class B
{
    public string Property4 { get; set; }
    public string Property5 { get; set; }
    public string Property6 { get; set; }

    [Attribute1]
    [Attribute2]
    [Attribute3]
    public string Foo { get; set; }
}

基本上Foo每次都有相同的属性,但copy-paste不是一个选项,因为它太容易出错。

在这个特定示例中,它可以从此类继承AB

public class C
{
    [Attribute1]
    [Attribute2]
    [Attribute3]
    public string Foo { get; set; }
}

但是拥有更多属性如Foo,这是无法实现的,因为C#不允许多重继承。

1 个答案:

答案 0 :(得分:4)

您可以考虑将C作为接口并使用您的属性装饰interface属性 - 这解决了多继承问题。

public interface IC
{
    [Attribute1]
    [Attribute2]
    [Attribute3]
    string Foo { get; set; }
}