哪种代码编程风格更好

Tan*_*ser 3 .net c# polymorphism

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

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

   public void SendNotificationForAction1(Action1 action) {}
   public void SendNotificationForAction2(Action2 action) {}
   public void SendNotificationForActionN(ActionN action) {}
Run Code Online (Sandbox Code Playgroud)

要么

   public void SendNotification(Object action) 
   {
       //here I will check type of action and do something
   }
Run Code Online (Sandbox Code Playgroud)

Fre*_*els 8

第一个是类型安全的,第二个不是.因此,如果我要在这两个选项之间做出选择,我会选择第一个选项.

另一方面,是不是可以采用完全不同的方法?在哪里有一个基类或接口Action,其他类派生自何处?接口或基类可以有一个' GetDetailsForNotification'方法,您可以在实现者中实现,并且可以在方法中使用该SendNotificationForAction方法.

像这样的东西,但是,当然,我不知道这在你的背景下是否可行:

interface IAction
{
   string GetDetailsForNotification();
}

public class Action : IAction{
   public string GetDetailsForNotification()
   {
        return "details from Action";
   }
}

public class Action2 : IAction{
   public string GetDetailsForNotification()
   {
        return "details from Action2";
   }
}


public void SendNotificationForAction(IAction action) {

   var details = action.GetDetailsForNotification();
   ...
}
Run Code Online (Sandbox Code Playgroud)


Ser*_*eit 8

我想这取决于:

发送通知的代码是或多或少相同的?然后我会选择:

public void SendNotificationFor<T>(T action) {}
Run Code Online (Sandbox Code Playgroud)

否则我可能会选择重载该方法:

public void SendNotification(Action1 action) {}
public void SendNotification(Action2 action) {}
public void SendNotification(ActionN action) {}
Run Code Online (Sandbox Code Playgroud)