有什么方法可以从事件订阅者返回值

时间:2018-10-17 22:40:45

标签: c# events delegates

我订阅了一些返回值的定制事件后,如何获得该返回值? (Logger内的productDetails)

void Logger()
{ 
    cart.ProductAddedEvent += DisplayAddedProduct;  
    //how do I get productDetails from DispalyAddedProduct() 
} 

string DisplayAddedProduct(NewProductArgs args)  
{  
    string productDetails = $"{args.Product.name} {args.Product.Price}";
    return productDetails  
}

2 个答案:

答案 0 :(得分:0)

  

GetInvocationList 返回此多播的调用列表   委托,按调用顺序。

     

尽管事件未发送回值,但这是可能的   根据需要

        static event Func<NewProductArgs, string> ProductAddedEvent;

        static void Main(string[] args)
        {
            ProductAddedEvent += Program_ProductAddedEvent;

            var productDelegate = ProductAddedEvent?.GetInvocationList().FirstOrDefault();

            productDelegate?.DynamicInvoke();
        }

        private static string Program_ProductAddedEvent(NewProductArgs arg)
        {
            return $"{args.Product.name} {args.Product.Price}";
        }

答案 1 :(得分:0)

您可以将返回值添加为NewProductArgs类的属性,并在调用事件后读取它们。

类似这样的东西:

class NewProductArgs: EventArgs
{
    public IList<string> ReturnValues { get; } = new List<string>();
    public Product Product { get; set; }
}

class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

class Cart
{
    public event EventHandler<NewProductArgs> ProductAddedEvent;
    public void Add(Product product)
    {
        var args = new NewProductArgs { Product = product };
        ProductAddedEvent?.Invoke(this, args);
        var retvals = args.ReturnValues; 
        foreach (var ret in retvals)
        {
            Console.WriteLine(ret);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        var cart = new Cart();
        cart.ProductAddedEvent += DisplayAddedProduct;
        cart.ProductAddedEvent += AnotherEventHandler;

        cart.Add(new Product { Name = "Product-1", Price = 100.0m });
        cart.Add(new Product { Name = "Product-2", Price = 200.0m });
    }

    static void AnotherEventHandler(object sender, NewProductArgs args)
    {
        args.ReturnValues.Add($"Handler2: {args.Product.Name} {args.Product.Price}");
    }

    static void DisplayAddedProduct(object sender, NewProductArgs args)
    {
        args.ReturnValues.Add($"Handler1 : {args.Product.Name} {args.Product.Price}");
    }
}