为什么使用属性而不是从接口(interface)继承? 实现接口(interface)不是比向 C# 添加全新概念(属性)更容易吗?
属性示例:
[Serializable]
public class MyObject {
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
界面示例:
public class MyObject: ISerializable {
public byte[] getBinaryData() { // some code }
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
最佳答案
您的示例并未涵盖属性提供的所有功能。使用接口(interface)
您无法表达有关类或方法的附加信息。您将需要为其使用属性。
来自MSDN
•Attributes add metadata to your program. Metadata is information about the types defined in a program. All .NET assemblies contain a specified set of metadata that describes the types and type members defined in the assembly. You can add custom attributes to specify any additional information that is required.
•You can apply one or more attributes to entire assemblies, modules, or smaller program elements such as classes and properties.
•Attributes can accept arguments in the same way as methods and properties.
•Your program can examine its own metadata or the metadata in other programs by using reflection.
关于c# - 为什么我应该使用属性而不是实现接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18315426/