c# - 哪种代码是更好的编程风格

标签 c# .net polymorphism

我有几个不同的对象,但我必须对它们执行类似的操作。 什么更好用: 1. 几个方法并使用这些对象作为类型参数。 2. 使用一种获取System.Object 作为参数的方法。在这个方法中,我将检查参数类型并执行一些操作。

例如,我应该为某些操作发送通知。我有对象 Action1、Action2、Action3...ActionN,其中包含这些操作的详细信息。我应该使用:

   public void SendNotificationForAction1(Action1 action) {}
   public void SendNotificationForAction2(Action2 action) {}
   public void SendNotificationForActionN(ActionN action) {}

   public void SendNotification(Object action) 
   {
       //here I will check type of action and do something
   }

最佳答案

我想这取决于:

发送通知的代码是否大致相同?那么我会选择:

public void SendNotificationFor<T>(T action) {}

否则我可能会选择 overload方法:

public void SendNotification(Action1 action) {}
public void SendNotification(Action2 action) {}
public void SendNotification(ActionN action) {}

关于c# - 哪种代码是更好的编程风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10105077/

相关文章:

C# 多态属性

Python:调用父实例方法

c# - LINQ to Entities 无法识别方法 'System.String get_Item(Int32)' 方法,并且无法将此方法翻译成存储表达式

c# - 按顺序使用数组获取文件

c# - Windows 8.1 商店应用程序的信用卡支付实现

c# - 将间接引用的程序集复制到输出目录 - 缺少程序集

sql - 如何处理将 DBNull 传递给函数?

c++ - 克隆指针 C++

c# - Dapper DynamicParameters 返回错误

c# - 检查 C# new() 初始化是否为 null?