Check if an object is a delegate

后端 未结 4 1028
一个人的身影
一个人的身影 2021-01-11 10:10

In .NET, Is there a way to check whether an object is of a delegate type?

I need this because I\'m logging the parameters of method calls, and I want to print

相关标签:
4条回答
  • 2021-01-11 10:21

    Sure, same as with any other type:

    if (foo is Delegate)
    

    Or for a type:

    if (typeof(Delegate).IsAssignableFrom(t))
    
    0 讨论(0)
  • 2021-01-11 10:22

    Yes. Check to see if the type inherits from System.Delegate. Here's a working sample with some simple testing thrown in to make sure we have a proper delegate object:

    using System;
    
    public class MyClass
    {
        delegate void DelegateType();
        public static void Main()
        {
            DelegateType obj = method;
            obj.Method.Invoke(null, null);
    
            if (obj is System.Delegate)
                Console.WriteLine("Type is a delegate");
            else        
                Console.WriteLine("Type is NOT a delegate");
        }
    
        private static void method() {Console.WriteLine("Invoked");}
    }
    
    0 讨论(0)
  • 2021-01-11 10:23

    This works perfectly for me

    class Test
        {
            public delegate void MyHandler(string x);
    
            public void RunTest()
            {
                var del = new MyHandler(Method);
                if (del is Delegate)
                {
                    Console.WriteLine(@"del is a delegate.");
                }
                else
                {
                    Console.WriteLine("del is not a delegate");
                }
    
            }
    
            private void Method(string myString)
            {
            }
        }
    
    0 讨论(0)
  • 2021-01-11 10:30

    You can just check whether obj is Delegate.
    All delegate types inherit the base Delegate class.

    0 讨论(0)
提交回复
热议问题