Check if an object is a delegate

浪子不回头ぞ 提交于 2020-05-23 07:56:27

问题


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 "(delegate)" for all parameters which are actions or functions.


回答1:


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)
        {
        }
    }



回答2:


Sure, same as with any other type:

if (foo is Delegate)

Or for a type:

if (typeof(Delegate).IsAssignableFrom(t))



回答3:


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




回答4:


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");}
}


来源:https://stackoverflow.com/questions/5819907/check-if-an-object-is-a-delegate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!