我有几个不同的对象,但我必须对它们执行类似的操作。 什么更好用: 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/