问题
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