c# - 为什么我应该使用属性而不是实现接口(interface)?

标签 c# serialization reflection interface attributes

为什么使用属性而不是从接口(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/

相关文章:

c# - Automapper 说缺少从 System.String 到 System.Char 的映射?但我看不到 Char 属性

python - Django REST 框架元组被解释为字符串?

c# - 通过套接字动态调用方法

c# - 不在两位数之间时去除小数点

c# - 从文件名获取路径

c# - 如何检测 WPF 中的 NumLock 开/关状态

c - 将结构体写入缓冲区

java - 如何将 DefaultMutableTreeNode (Java) 序列化为 JSON?

c# - Windows Mobile 项目中的 System.Reflection

c# - 从没有反射的c#源代码中提取属性