问题描述
昨天,我在 Pluralsight 上观看了 RabbitMQ 课程。我注意到他们使用 Action 委托作为方法参数来设置来配置。所以,方法中已经有了一些设置,如果有需要添加更多的配置,我们可以通过Action委托参数来传递。他们使用 Action Delegate 作为带有接口的参数的方式对我来说是新的。因此,我尝试在测试控制台应用程序中复制它。不确定,我是否完美地实现了它。
class Program
{
static void Main(string[] args)
{
// If I want to set/add configuration,I can send it by Action delegate.
Program.DoSomeConfiguration((cdd) =>
{
cdd.SetConfig("New Config");
});
// If I do not want to set new configuration and just want to execute it.
// Call 'DoSomeConfiguration' with null.
//Program.DoSomeConfiguration();
}
public static void DoSomeConfiguration(Action<ITest> actionMy = null)
{
ConfigClass obj = new ConfigClass();
obj.MyConfigurations.Add("Old Config");
obj.SetConfig();
Console.WriteLine("**************************************");
actionMy?.Invoke(obj);
}
}
public interface ITest
{
void SetConfig(string config);
}
public class ConfigClass : ITest
{
public List<string> MyConfigurations { get; set; }
public ConfigClass()
{
MyConfigurations = new List<string>();
}
public void SetConfig(string config = null)
{
if (config != null)
{
MyConfigurations.Add(config);
}
foreach (var configuration in MyConfigurations)
{
Console.WriteLine($"config {configuration}");
}
}
}
MyCode 解释:我在“DoSomeConfiguration”方法中有一些默认配置。如果有人想添加更多的配置,可以通过Action Delegate传递。
我是否正确使用了它?
解决方法
不知道您如何使用这些配置。因为 ConfigClass obj 在 DoSomeConfiguration 之外是不可访问的。关于 ConfigClass - MyConfigurations 不应该被公开,并且 SetConfig 有不止一种责任 - 发送配置并打印出配置值(我假设当传递 null 的目的只是为了打印出配置值)