我试图在许多类中使用同一组属性。如何在 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
不是一个选项,因为它太容易出错。
在这个特定的示例中,它可以从此类继承 A
和 B
:
public class C
{
[Attribute1]
[Attribute2]
[Attribute3]
public string Foo { get; set; }
}
但是如果有更多的属性,比如 Foo
,这就无法实现,因为 C# 不允许多重继承。
最佳答案
您可能会考虑使 C
成为接口(interface)并使用您的属性装饰接口(interface)属性 - 这解决了多重继承问题。
public interface IC
{
[Attribute1]
[Attribute2]
[Attribute3]
string Foo { get; set; }
}
关于c# - 在 C# 中的许多类中使用相同的一堆属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31834609/