How to declare generic event for generic delegate in c#

后端 未结 6 1992
不思量自难忘°
不思量自难忘° 2020-12-17 16:55

I have a user control which deals with fileupload. I have defined a delegate as follows

public delegate void FileUploadSuccess(T value,FileUploadTyp         


        
6条回答
  •  情歌与酒
    2020-12-17 17:44

    There is a generic EventHandler class in the .Net Framework just for this purpose:

    using System;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Counter c = new Counter(new Random().Next(10));
                c.ThresholdReached += c_ThresholdReached;
    
                Console.WriteLine("press 'a' key to increase total");
                while (Console.ReadKey(true).KeyChar == 'a')
                {
                    Console.WriteLine("adding one");
                    c.Add(1);
                }
            }
    
            static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e)
            {
                Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold,  e.TimeReached);
                Environment.Exit(0);
            }
        }
    
        class Counter
        {
            private int threshold;
            private int total;
    
            public Counter(int passedThreshold)
            {
                threshold = passedThreshold;
            }
    
            public void Add(int x)
            {
                total += x;
                if (total >= threshold)
                {
                    ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
                    args.Threshold = threshold;
                    args.TimeReached = DateTime.Now;
                    OnThresholdReached(args);
                }
            }
    
            protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
            {
                EventHandler handler = ThresholdReached;
                if (handler != null)
                {
                    handler(this, e);
                }
            }
    
            public event EventHandler ThresholdReached;
        }
    
        public class ThresholdReachedEventArgs : EventArgs
        {
            public int Threshold { get; set; }
            public DateTime TimeReached { get; set; }
        }
    }
    

    source: https://docs.microsoft.com/en-us/dotnet/api/system.eventhandler-1

提交回复
热议问题